1 package DBIx::Class::Storage::DBI;
3 use base 'DBIx::Class::Storage';
8 use SQL::Abstract::Limit;
9 use DBIx::Class::Storage::DBI::Cursor;
11 use Carp::Clan qw/DBIx::Class/;
15 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
17 use base qw/SQL::Abstract::Limit/;
20 my ($self, $table, $fields, $where, $order, @rest) = @_;
21 $table = $self->_quote($table) unless ref($table);
22 @rest = (-1) unless defined $rest[0];
23 die "LIMIT 0 Does Not Compute" if $rest[0] == 0;
24 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
25 local $self->{having_bind} = [];
26 my ($sql, @ret) = $self->SUPER::select(
27 $table, $self->_recurse_fields($fields), $where, $order, @rest
29 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
35 $table = $self->_quote($table) unless ref($table);
36 $self->SUPER::insert($table, @_);
42 $table = $self->_quote($table) unless ref($table);
43 $self->SUPER::update($table, @_);
49 $table = $self->_quote($table) unless ref($table);
50 $self->SUPER::delete($table, @_);
56 return $_[1].$self->_order_by($_[2]);
58 return $self->SUPER::_emulate_limit(@_);
63 my ($self, $fields) = @_;
64 my $ref = ref $fields;
65 return $self->_quote($fields) unless $ref;
66 return $$fields if $ref eq 'SCALAR';
68 if ($ref eq 'ARRAY') {
69 return join(', ', map { $self->_recurse_fields($_) } @$fields);
70 } elsif ($ref eq 'HASH') {
71 foreach my $func (keys %$fields) {
72 return $self->_sqlcase($func)
73 .'( '.$self->_recurse_fields($fields->{$func}).' )';
82 if (ref $_[0] eq 'HASH') {
83 if (defined $_[0]->{group_by}) {
84 $ret = $self->_sqlcase(' group by ')
85 .$self->_recurse_fields($_[0]->{group_by});
87 if (defined $_[0]->{having}) {
89 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
90 push(@{$self->{having_bind}}, @extra);
91 $ret .= $self->_sqlcase(' having ').$frag;
93 if (defined $_[0]->{order_by}) {
94 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
96 } elsif(ref $_[0] eq 'SCALAR') {
97 $ret = $self->_sqlcase(' order by ').${ $_[0] };
99 $ret = $self->SUPER::_order_by(@_);
104 sub _order_directions {
105 my ($self, $order) = @_;
106 $order = $order->{order_by} if ref $order eq 'HASH';
107 return $self->SUPER::_order_directions($order);
111 my ($self, $from) = @_;
112 if (ref $from eq 'ARRAY') {
113 return $self->_recurse_from(@$from);
114 } elsif (ref $from eq 'HASH') {
115 return $self->_make_as($from);
117 return $from; # would love to quote here but _table ends up getting called
118 # twice during an ->select without a limit clause due to
119 # the way S::A::Limit->select works. should maybe consider
120 # bypassing this and doing S::A::select($self, ...) in
121 # our select method above. meantime, quoting shims have
122 # been added to select/insert/update/delete here
127 my ($self, $from, @join) = @_;
129 push(@sqlf, $self->_make_as($from));
130 foreach my $j (@join) {
133 # check whether a join type exists
134 my $join_clause = '';
135 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
136 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
138 $join_clause = ' JOIN ';
140 push(@sqlf, $join_clause);
142 if (ref $to eq 'ARRAY') {
143 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
145 push(@sqlf, $self->_make_as($to));
147 push(@sqlf, ' ON ', $self->_join_condition($on));
149 return join('', @sqlf);
153 my ($self, $from) = @_;
154 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
155 reverse each %{$self->_skip_options($from)});
159 my ($self, $hash) = @_;
161 $clean_hash->{$_} = $hash->{$_}
162 for grep {!/^-/} keys %$hash;
166 sub _join_condition {
167 my ($self, $cond) = @_;
168 if (ref $cond eq 'HASH') {
171 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
173 return $self->_recurse_where(\%j);
174 } elsif (ref $cond eq 'ARRAY') {
175 return join(' OR ', map { $self->_join_condition($_) } @$cond);
177 die "Can't handle this yet!";
182 my ($self, $label) = @_;
183 return '' unless defined $label;
184 return "*" if $label eq '*';
185 return $label unless $self->{quote_char};
186 if(ref $self->{quote_char} eq "ARRAY"){
187 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
188 if !defined $self->{name_sep};
189 my $sep = $self->{name_sep};
190 return join($self->{name_sep},
191 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
192 split(/\Q$sep\E/,$label));
194 return $self->SUPER::_quote($label);
200 $_[0] =~ s/SELECT (.*?) FROM/
201 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
202 $self->SUPER::_RowNum(@_);
205 # Accessor for setting limit dialect. This is useful
206 # for JDBC-bridge among others where the remote SQL-dialect cannot
207 # be determined by the name of the driver alone.
211 $self->{limit_dialect} = shift if @_;
212 return $self->{limit_dialect};
217 $self->{quote_char} = shift if @_;
218 return $self->{quote_char};
223 $self->{name_sep} = shift if @_;
224 return $self->{name_sep};
230 package DBIx::Class::Storage::DBI::DebugCallback;
233 my ($self, $string) = @_;
234 $string =~ m/^(\w+)/;
235 ${$self}->($1, $string);
238 } # End of BEGIN block
240 use base qw/DBIx::Class/;
242 __PACKAGE__->load_components(qw/AccessorGroup/);
244 __PACKAGE__->mk_group_accessors('simple' =>
245 qw/connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
246 cursor on_connect_do transaction_depth/);
249 my $new = bless({}, ref $_[0] || $_[0]);
250 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
251 $new->transaction_depth(0);
252 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
253 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
254 $new->debugfh(IO::File->new($1, 'w'))
255 or $new->throw_exception("Cannot open trace file $1");
257 $new->debugfh(IO::File->new('>&STDERR'));
259 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
263 sub throw_exception {
264 my ($self, $msg) = @_;
270 DBIx::Class::Storage::DBI - DBI storage handler
276 This class represents the connection to the database
284 Executes the sql statements given as a listref on every db connect.
288 Causes SQL trace information to be emitted on C<debugfh> filehandle
289 (or C<STDERR> if C<debugfh> has not specifically been set).
293 Sets or retrieves the filehandle used for trace/debug output. This
294 should be an IO::Handle compatible object (only the C<print> method is
295 used). Initially set to be STDERR - although see information on the
296 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
300 Sets a callback to be executed each time a statement is run; takes a sub
301 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
302 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
308 my ($self, $cb) = @_;
309 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
310 $self->debugfh($cb_obj);
316 if( $self->connected ) {
317 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
318 $self->_dbh->disconnect;
326 if(my $dbh = $self->_dbh) {
327 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
328 $self->_sql_maker(undef);
329 return $self->_dbh(undef);
331 elsif($self->_conn_pid != $$) {
332 $self->_dbh->{InactiveDestroy} = 1;
333 $self->_sql_maker(undef);
334 return $self->_dbh(undef)
336 return ($dbh->FETCH('Active') && $dbh->ping);
342 sub ensure_connected {
345 unless ($self->connected) {
346 $self->_populate_dbh;
352 Returns the dbh - a data base handle of class L<DBI>.
359 $self->ensure_connected;
365 unless ($self->_sql_maker) {
366 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
368 return $self->_sql_maker;
373 my @info = @{$self->connect_info || []};
374 $self->_dbh($self->_connect(@info));
375 my $driver = $self->_dbh->{Driver}->{Name};
376 eval "require DBIx::Class::Storage::DBI::${driver}";
378 bless $self, "DBIx::Class::Storage::DBI::${driver}";
380 # if on-connect sql statements are given execute them
381 foreach my $sql_statement (@{$self->on_connect_do || []}) {
382 $self->_dbh->do($sql_statement);
385 $self->_conn_pid($$);
386 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
390 my ($self, @info) = @_;
392 $self->throw_exception("You failed to provide any connection info")
395 my ($old_connect_via, $dbh);
397 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
398 $old_connect_via = $DBI::connect_via;
399 $DBI::connect_via = 'connect';
403 if(ref $info[0] eq 'CODE') {
407 $dbh = DBI->connect(@info);
411 $DBI::connect_via = $old_connect_via if $old_connect_via;
414 $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
422 Calls begin_work on the current dbh.
424 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
425 an entire code block to be executed transactionally.
431 if ($self->{transaction_depth}++ == 0) {
432 my $dbh = $self->dbh;
433 if ($dbh->{AutoCommit}) {
434 $self->debugfh->print("BEGIN WORK\n")
443 Issues a commit against the current dbh.
449 if ($self->{transaction_depth} == 0) {
450 my $dbh = $self->dbh;
451 unless ($dbh->{AutoCommit}) {
452 $self->debugfh->print("COMMIT\n")
458 if (--$self->{transaction_depth} == 0) {
459 $self->debugfh->print("COMMIT\n")
468 Issues a rollback against the current dbh. A nested rollback will
469 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
470 which allows the rollback to propagate to the outermost transaction.
478 if ($self->{transaction_depth} == 0) {
479 my $dbh = $self->dbh;
480 unless ($dbh->{AutoCommit}) {
481 $self->debugfh->print("ROLLBACK\n")
487 if (--$self->{transaction_depth} == 0) {
488 $self->debugfh->print("ROLLBACK\n")
490 $self->dbh->rollback;
493 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
500 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
501 $error =~ /$exception_class/ and $self->throw_exception($error);
502 $self->{transaction_depth} = 0; # ensure that a failed rollback
503 $self->throw_exception($error); # resets the transaction depth
508 my ($self, $op, $extra_bind, $ident, @args) = @_;
509 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
510 unshift(@bind, @$extra_bind) if $extra_bind;
512 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
513 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
515 my $sth = eval { $self->sth($sql,$op) };
518 $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql");
521 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
524 $rv = eval { $sth->execute(@bind) };
527 $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
530 $self->throw_exception("'$sql' did not generate a statement.");
532 return (wantarray ? ($rv, $sth, @bind) : $rv);
536 my ($self, $ident, $to_insert) = @_;
537 $self->throw_exception(
538 "Couldn't insert ".join(', ',
539 map "$_ => $to_insert->{$_}", keys %$to_insert
541 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
546 return shift->_execute('update' => [], @_);
550 return shift->_execute('delete' => [], @_);
554 my ($self, $ident, $select, $condition, $attrs) = @_;
555 my $order = $attrs->{order_by};
556 if (ref $condition eq 'SCALAR') {
557 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
559 if (exists $attrs->{group_by} || $attrs->{having}) {
561 group_by => $attrs->{group_by},
562 having => $attrs->{having},
563 ($order ? (order_by => $order) : ())
566 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
567 if ($attrs->{software_limit} ||
568 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
569 $attrs->{software_limit} = 1;
571 $self->throw_exception("rows attribute must be positive if present")
572 if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
573 push @args, $attrs->{rows}, $attrs->{offset};
575 return $self->_execute(@args);
580 my ($ident, $select, $condition, $attrs) = @_;
581 return $self->cursor->new($self, \@_, $attrs);
584 # Need to call finish() to work round broken DBDs
588 my ($rv, $sth, @bind) = $self->_select(@_);
589 my @row = $sth->fetchrow_array;
595 my ($self, $sql) = @_;
596 # 3 is the if_active parameter which avoids active sth re-use
597 return $self->dbh->prepare_cached($sql, {}, 3);
600 =head2 columns_info_for
602 Returns database type info for a given table columns.
606 sub columns_info_for {
607 my ($self, $table) = @_;
609 my $dbh = $self->dbh;
611 if ($dbh->can('column_info')) {
613 my $old_raise_err = $dbh->{RaiseError};
614 my $old_print_err = $dbh->{PrintError};
615 $dbh->{RaiseError} = 1;
616 $dbh->{PrintError} = 0;
618 my $sth = $dbh->column_info( undef, undef, $table, '%' );
620 while ( my $info = $sth->fetchrow_hashref() ){
622 $column_info{data_type} = $info->{TYPE_NAME};
623 $column_info{size} = $info->{COLUMN_SIZE};
624 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
625 $column_info{default_value} = $info->{COLUMN_DEF};
627 $result{$info->{COLUMN_NAME}} = \%column_info;
630 $dbh->{RaiseError} = $old_raise_err;
631 $dbh->{PrintError} = $old_print_err;
632 return \%result if !$@;
636 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
638 my @columns = @{$sth->{NAME_lc}};
639 for my $i ( 0 .. $#columns ){
641 my $type_num = $sth->{TYPE}->[$i];
643 if(defined $type_num && $dbh->can('type_info')) {
644 my $type_info = $dbh->type_info($type_num);
645 $type_name = $type_info->{TYPE_NAME} if $type_info;
647 $column_info{data_type} = $type_name ? $type_name : $type_num;
648 $column_info{size} = $sth->{PRECISION}->[$i];
649 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
651 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
652 $column_info{data_type} = $1;
653 $column_info{size} = $2;
656 $result{$columns[$i]} = \%column_info;
663 my ($self, $row) = @_;
665 return $self->dbh->func('last_insert_rowid');
669 sub sqlt_type { shift->dbh->{Driver}->{Name} }
671 sub deployment_statements {
672 my ($self, $schema, $type, $sqltargs) = @_;
673 $type ||= $self->sqlt_type;
674 eval "use SQL::Translator";
675 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
676 eval "use SQL::Translator::Parser::DBIx::Class;";
677 $self->throw_exception($@) if $@;
678 eval "use SQL::Translator::Producer::${type};";
679 $self->throw_exception($@) if $@;
680 my $tr = SQL::Translator->new(%$sqltargs);
681 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
682 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
686 my ($self, $schema, $type, $sqltargs) = @_;
687 foreach my $statement ( $self->deployment_statements($schema, $type, $sqltargs) ) {
688 for ( split(";\n", $statement)) {
689 $self->debugfh->print("$_\n") if $self->debug;
690 $self->dbh->do($_) or warn "SQL was:\n $_";
695 sub DESTROY { shift->disconnect }
699 =head1 ENVIRONMENT VARIABLES
701 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
703 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
704 is produced (as when the L<debug> method is set).
706 If the value is of the form C<1=/path/name> then the trace output is
707 written to the file C</path/name>.
711 Matt S. Trout <mst@shadowcatsystems.co.uk>
713 Andy Grundman <andy@hybridized.org>
717 You may distribute this code under the same terms as Perl itself.