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 @rest = (-1) unless defined $rest[0];
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;
31 return $_[1].$self->_order_by($_[2]);
33 return $self->SUPER::_emulate_limit(@_);
38 my ($self, $fields) = @_;
39 my $ref = ref $fields;
40 return $self->_quote($fields) unless $ref;
41 return $$fields if $ref eq 'SCALAR';
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}).' )';
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});
62 if (defined $_[0]->{having}) {
64 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
65 push(@{$self->{having_bind}}, @extra);
66 $ret .= $self->_sqlcase(' having ').$frag;
68 if (defined $_[0]->{order_by}) {
69 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
71 } elsif(ref $_[0] eq 'SCALAR') {
72 $ret = $self->_sqlcase(' order by ').${ $_[0] };
74 $ret = $self->SUPER::_order_by(@_);
79 sub _order_directions {
80 my ($self, $order) = @_;
81 $order = $order->{order_by} if ref $order eq 'HASH';
82 return $self->SUPER::_order_directions($order);
86 my ($self, $from) = @_;
87 if (ref $from eq 'ARRAY') {
88 return $self->_recurse_from(@$from);
89 } elsif (ref $from eq 'HASH') {
90 return $self->_make_as($from);
97 my ($self, $from, @join) = @_;
99 push(@sqlf, $self->_make_as($from));
100 foreach my $j (@join) {
103 # check whether a join type exists
104 my $join_clause = '';
105 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
106 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
108 $join_clause = ' JOIN ';
110 push(@sqlf, $join_clause);
112 if (ref $to eq 'ARRAY') {
113 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
115 push(@sqlf, $self->_make_as($to));
117 push(@sqlf, ' ON ', $self->_join_condition($on));
119 return join('', @sqlf);
123 my ($self, $from) = @_;
124 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
125 reverse each %{$self->_skip_options($from)});
129 my ($self, $hash) = @_;
131 $clean_hash->{$_} = $hash->{$_}
132 for grep {!/^-/} keys %$hash;
136 sub _join_condition {
137 my ($self, $cond) = @_;
138 if (ref $cond eq 'HASH') {
140 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
141 return $self->_recurse_where(\%j);
142 } elsif (ref $cond eq 'ARRAY') {
143 return join(' OR ', map { $self->_join_condition($_) } @$cond);
145 die "Can't handle this yet!";
150 my ($self, $label) = @_;
151 return '' unless defined $label;
152 return "*" if $label eq '*';
153 return $label unless $self->{quote_char};
154 if(ref $self->{quote_char} eq "ARRAY"){
155 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
156 if !defined $self->{name_sep};
157 my $sep = $self->{name_sep};
158 return join($self->{name_sep},
159 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
160 split(/\Q$sep\E/,$label));
162 return $self->SUPER::_quote($label);
168 $_[0] =~ s/SELECT (.*?) FROM/
169 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
170 $self->SUPER::_RowNum(@_);
173 # Accessor for setting limit dialect. This is useful
174 # for JDBC-bridge among others where the remote SQL-dialect cannot
175 # be determined by the name of the driver alone.
179 $self->{limit_dialect} = shift if @_;
180 return $self->{limit_dialect};
185 $self->{quote_char} = shift if @_;
186 return $self->{quote_char};
191 $self->{name_sep} = shift if @_;
192 return $self->{name_sep};
198 package DBIx::Class::Storage::DBI::DebugCallback;
201 my ($self, $string) = @_;
202 $string =~ m/^(\w+)/;
203 ${$self}->($1, $string);
206 } # End of BEGIN block
208 use base qw/DBIx::Class/;
210 __PACKAGE__->load_components(qw/AccessorGroup/);
212 __PACKAGE__->mk_group_accessors('simple' =>
213 qw/connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
214 cursor on_connect_do transaction_depth/);
217 my $new = bless({}, ref $_[0] || $_[0]);
218 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
219 $new->transaction_depth(0);
220 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
221 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
222 $new->debugfh(IO::File->new($1, 'w')) || $new->throw_exception("Cannot open trace file $1");
224 $new->debugfh(IO::File->new('>&STDERR'));
226 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
230 sub throw_exception {
231 my ($self, $msg) = @_;
237 DBIx::Class::Storage::DBI - DBI storage handler
243 This class represents the connection to the database
251 Executes the sql statements given as a listref on every db connect.
255 Causes SQL trace information to be emitted on C<debugfh> filehandle
256 (or C<STDERR> if C<debugfh> has not specifically been set).
260 Sets or retrieves the filehandle used for trace/debug output. This
261 should be an IO::Handle compatible object (only the C<print> method is
262 used). Initially set to be STDERR - although see information on the
263 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
267 Sets a callback to be executed each time a statement is run; takes a sub
268 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
269 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
275 my ($self, $cb) = @_;
276 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
277 $self->debugfh($cb_obj);
283 if( $self->connected ) {
284 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
285 $self->_dbh->disconnect;
293 if(my $dbh = $self->_dbh) {
294 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
295 $self->_sql_maker(undef);
296 return $self->_dbh(undef);
298 elsif($self->_conn_pid != $$) {
299 $self->_dbh->{InactiveDestroy} = 1;
300 $self->_sql_maker(undef);
301 return $self->_dbh(undef)
303 return ($dbh->FETCH('Active') && $dbh->ping);
309 sub ensure_connected {
312 unless ($self->connected) {
313 $self->_populate_dbh;
320 $self->ensure_connected;
326 unless ($self->_sql_maker) {
327 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
329 return $self->_sql_maker;
334 my @info = @{$self->connect_info || []};
335 $self->_dbh($self->_connect(@info));
336 my $driver = $self->_dbh->{Driver}->{Name};
337 eval "require DBIx::Class::Storage::DBI::${driver}";
339 bless $self, "DBIx::Class::Storage::DBI::${driver}";
341 # if on-connect sql statements are given execute them
342 foreach my $sql_statement (@{$self->on_connect_do || []}) {
343 $self->_dbh->do($sql_statement);
346 $self->_conn_pid($$);
347 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
351 my ($self, @info) = @_;
353 $self->throw_exception("You failed to provide any connection info")
356 my ($old_connect_via, $dbh);
358 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
359 $old_connect_via = $DBI::connect_via;
360 $DBI::connect_via = 'connect';
363 if(ref $info[0] eq 'CODE') {
367 $dbh = DBI->connect(@info);
370 $DBI::connect_via = $old_connect_via if $old_connect_via;
372 $self->throw_exception("DBI Connection failed: $DBI::errstr")
380 Calls begin_work on the current dbh.
382 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
383 an entire code block to be executed transactionally.
389 $self->dbh->begin_work
390 if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
395 Issues a commit against the current dbh.
401 if ($self->{transaction_depth} == 0) {
402 $self->dbh->commit unless $self->dbh->{AutoCommit};
405 $self->dbh->commit if --$self->{transaction_depth} == 0;
411 Issues a rollback against the current dbh. A nested rollback will
412 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
413 which allows the rollback to propagate to the outermost transaction.
421 if ($self->{transaction_depth} == 0) {
422 $self->dbh->rollback unless $self->dbh->{AutoCommit};
425 --$self->{transaction_depth} == 0 ?
426 $self->dbh->rollback :
427 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
433 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
434 $error =~ /$exception_class/ and $self->throw_exception($error);
435 $self->{transaction_depth} = 0; # ensure that a failed rollback
436 $self->throw_exception($error); # resets the transaction depth
441 my ($self, $op, $extra_bind, $ident, @args) = @_;
442 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
443 unshift(@bind, @$extra_bind) if $extra_bind;
445 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
446 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
448 my $sth = $self->sth($sql,$op);
449 $self->throw_exception("no sth generated via sql: $sql") unless $sth;
450 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
453 $rv = $sth->execute(@bind) or $self->throw_exception("Error executing '$sql': " . $sth->errstr);
455 $self->throw_exception("'$sql' did not generate a statement.");
457 return (wantarray ? ($rv, $sth, @bind) : $rv);
461 my ($self, $ident, $to_insert) = @_;
462 $self->throw_exception( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
463 unless ($self->_execute('insert' => [], $ident, $to_insert));
468 return shift->_execute('update' => [], @_);
472 return shift->_execute('delete' => [], @_);
476 my ($self, $ident, $select, $condition, $attrs) = @_;
477 my $order = $attrs->{order_by};
478 if (ref $condition eq 'SCALAR') {
479 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
481 if (exists $attrs->{group_by} || $attrs->{having}) {
482 $order = { group_by => $attrs->{group_by},
483 having => $attrs->{having},
484 ($order ? (order_by => $order) : ()) };
486 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
487 if ($attrs->{software_limit} ||
488 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
489 $attrs->{software_limit} = 1;
491 push @args, $attrs->{rows}, $attrs->{offset};
493 return $self->_execute(@args);
498 my ($ident, $select, $condition, $attrs) = @_;
499 return $self->cursor->new($self, \@_, $attrs);
502 # Need to call finish() to work round broken DBDs
506 my ($rv, $sth, @bind) = $self->_select(@_);
507 my @row = $sth->fetchrow_array;
513 my ($self, $sql) = @_;
514 # 3 is the if_active parameter which avoids active sth re-use
515 return $self->dbh->prepare_cached($sql, {}, 3);
518 =head2 columns_info_for
520 Returns database type info for a given table columns.
524 sub columns_info_for {
525 my ($self, $table) = @_;
527 if ($self->dbh->can('column_info')) {
529 my $old_raise_err = $self->dbh->{RaiseError};
530 my $old_print_err = $self->dbh->{PrintError};
531 $self->dbh->{RaiseError} = 1;
532 $self->dbh->{PrintError} = 0;
534 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
536 while ( my $info = $sth->fetchrow_hashref() ){
538 $column_info{data_type} = $info->{TYPE_NAME};
539 $column_info{size} = $info->{COLUMN_SIZE};
540 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
541 $column_info{default_value} = $info->{COLUMN_DEF};
543 $result{$info->{COLUMN_NAME}} = \%column_info;
546 $self->dbh->{RaiseError} = $old_raise_err;
547 $self->dbh->{PrintError} = $old_print_err;
548 return \%result if !$@;
552 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
554 my @columns = @{$sth->{NAME_lc}};
555 for my $i ( 0 .. $#columns ){
557 my $type_num = $sth->{TYPE}->[$i];
559 if(defined $type_num && $self->dbh->can('type_info')) {
560 my $type_info = $self->dbh->type_info($type_num);
561 $type_name = $type_info->{TYPE_NAME} if $type_info;
563 $column_info{data_type} = $type_name ? $type_name : $type_num;
564 $column_info{size} = $sth->{PRECISION}->[$i];
565 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
567 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
568 $column_info{data_type} = $1;
569 $column_info{size} = $2;
572 $result{$columns[$i]} = \%column_info;
579 my ($self, $row) = @_;
581 return $self->dbh->func('last_insert_rowid');
585 sub sqlt_type { shift->dbh->{Driver}->{Name} }
587 sub deployment_statements {
588 my ($self, $schema, $type, $sqltargs) = @_;
589 $type ||= $self->sqlt_type;
590 eval "use SQL::Translator";
591 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
592 eval "use SQL::Translator::Parser::DBIx::Class;";
593 $self->throw_exception($@) if $@;
594 eval "use SQL::Translator::Producer::${type};";
595 $self->throw_exception($@) if $@;
596 my $tr = SQL::Translator->new(%$sqltargs);
597 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
598 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
602 my ($self, $schema, $type, $sqltargs) = @_;
603 foreach(split(";\n", $self->deployment_statements($schema, $type, $sqltargs))) {
604 $self->debugfh->print("$_\n") if $self->debug;
605 $self->dbh->do($_) or warn "SQL was:\n $_";
609 sub DESTROY { shift->disconnect }
613 =head1 ENVIRONMENT VARIABLES
615 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
617 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
618 is produced (as when the L<debug> method is set).
620 If the value is of the form C<1=/path/name> then the trace output is
621 written to the file C</path/name>.
625 Matt S. Trout <mst@shadowcatsystems.co.uk>
627 Andy Grundman <andy@hybridized.org>
631 You may distribute this code under the same terms as Perl itself.