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 local $self->{having_bind} = [];
24 my ($sql, @ret) = $self->SUPER::select(
25 $table, $self->_recurse_fields($fields), $where, $order, @rest
27 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
33 $table = $self->_quote($table) unless ref($table);
34 $self->SUPER::insert($table, @_);
40 $table = $self->_quote($table) unless ref($table);
41 $self->SUPER::update($table, @_);
47 $table = $self->_quote($table) unless ref($table);
48 $self->SUPER::delete($table, @_);
54 return $_[1].$self->_order_by($_[2]);
56 return $self->SUPER::_emulate_limit(@_);
61 my ($self, $fields) = @_;
62 my $ref = ref $fields;
63 return $self->_quote($fields) unless $ref;
64 return $$fields if $ref eq 'SCALAR';
66 if ($ref eq 'ARRAY') {
67 return join(', ', map { $self->_recurse_fields($_) } @$fields);
68 } elsif ($ref eq 'HASH') {
69 foreach my $func (keys %$fields) {
70 return $self->_sqlcase($func)
71 .'( '.$self->_recurse_fields($fields->{$func}).' )';
80 if (ref $_[0] eq 'HASH') {
81 if (defined $_[0]->{group_by}) {
82 $ret = $self->_sqlcase(' group by ')
83 .$self->_recurse_fields($_[0]->{group_by});
85 if (defined $_[0]->{having}) {
87 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
88 push(@{$self->{having_bind}}, @extra);
89 $ret .= $self->_sqlcase(' having ').$frag;
91 if (defined $_[0]->{order_by}) {
92 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
94 } elsif(ref $_[0] eq 'SCALAR') {
95 $ret = $self->_sqlcase(' order by ').${ $_[0] };
97 $ret = $self->SUPER::_order_by(@_);
102 sub _order_directions {
103 my ($self, $order) = @_;
104 $order = $order->{order_by} if ref $order eq 'HASH';
105 return $self->SUPER::_order_directions($order);
109 my ($self, $from) = @_;
110 if (ref $from eq 'ARRAY') {
111 return $self->_recurse_from(@$from);
112 } elsif (ref $from eq 'HASH') {
113 return $self->_make_as($from);
115 return $from; # would love to quote here but _table ends up getting called
116 # twice during an ->select without a limit clause due to
117 # the way S::A::Limit->select works. should maybe consider
118 # bypassing this and doing S::A::select($self, ...) in
119 # our select method above. meantime, quoting shims have
120 # been added to select/insert/update/delete here
125 my ($self, $from, @join) = @_;
127 push(@sqlf, $self->_make_as($from));
128 foreach my $j (@join) {
131 # check whether a join type exists
132 my $join_clause = '';
133 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
134 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
136 $join_clause = ' JOIN ';
138 push(@sqlf, $join_clause);
140 if (ref $to eq 'ARRAY') {
141 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
143 push(@sqlf, $self->_make_as($to));
145 push(@sqlf, ' ON ', $self->_join_condition($on));
147 return join('', @sqlf);
151 my ($self, $from) = @_;
152 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
153 reverse each %{$self->_skip_options($from)});
157 my ($self, $hash) = @_;
159 $clean_hash->{$_} = $hash->{$_}
160 for grep {!/^-/} keys %$hash;
164 sub _join_condition {
165 my ($self, $cond) = @_;
166 if (ref $cond eq 'HASH') {
169 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
171 return $self->_recurse_where(\%j);
172 } elsif (ref $cond eq 'ARRAY') {
173 return join(' OR ', map { $self->_join_condition($_) } @$cond);
175 die "Can't handle this yet!";
180 my ($self, $label) = @_;
181 return '' unless defined $label;
182 return "*" if $label eq '*';
183 return $label unless $self->{quote_char};
184 if(ref $self->{quote_char} eq "ARRAY"){
185 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
186 if !defined $self->{name_sep};
187 my $sep = $self->{name_sep};
188 return join($self->{name_sep},
189 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
190 split(/\Q$sep\E/,$label));
192 return $self->SUPER::_quote($label);
198 $_[0] =~ s/SELECT (.*?) FROM/
199 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
200 $self->SUPER::_RowNum(@_);
203 # Accessor for setting limit dialect. This is useful
204 # for JDBC-bridge among others where the remote SQL-dialect cannot
205 # be determined by the name of the driver alone.
209 $self->{limit_dialect} = shift if @_;
210 return $self->{limit_dialect};
215 $self->{quote_char} = shift if @_;
216 return $self->{quote_char};
221 $self->{name_sep} = shift if @_;
222 return $self->{name_sep};
228 package DBIx::Class::Storage::DBI::DebugCallback;
231 my ($self, $string) = @_;
232 $string =~ m/^(\w+)/;
233 ${$self}->($1, $string);
236 } # End of BEGIN block
238 use base qw/DBIx::Class/;
240 __PACKAGE__->load_components(qw/AccessorGroup/);
242 __PACKAGE__->mk_group_accessors('simple' =>
243 qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
244 cursor on_connect_do transaction_depth/);
247 my $new = bless({}, ref $_[0] || $_[0]);
248 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
249 $new->transaction_depth(0);
250 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
251 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
252 $new->debugfh(IO::File->new($1, 'w'))
253 or $new->throw_exception("Cannot open trace file $1");
255 $new->debugfh(IO::File->new('>&STDERR'));
257 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
261 sub throw_exception {
262 my ($self, $msg) = @_;
268 DBIx::Class::Storage::DBI - DBI storage handler
274 This class represents the connection to the database
282 Connection information arrayref. Can either be the same arguments
283 one would pass to DBI->connect, or a code-reference which returns
284 a connected database handle. In either case, there is an optional
285 final element in the arrayref, which can hold a hashref of
286 connection-specific Storage::DBI options. These include
287 C<on_connect_do>, and the sql_maker options C<limit_dialect>,
288 C<quote_char>, and C<name_sep>. Examples:
290 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
291 ->connect_info(sub { DBI->connect(...) });
292 ->connect_info([ 'dbi:Pg:dbname=foo',
296 { quote_char => q{`}, name_sep => q{@} },
301 Executes the sql statements given as a listref on every db connect.
305 Causes SQL trace information to be emitted on C<debugfh> filehandle
306 (or C<STDERR> if C<debugfh> has not specifically been set).
310 Sets or retrieves the filehandle used for trace/debug output. This
311 should be an IO::Handle compatible object (only the C<print> method is
312 used). Initially set to be STDERR - although see information on the
313 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
317 Sets a callback to be executed each time a statement is run; takes a sub
318 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
319 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
325 my ($self, $cb) = @_;
326 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
327 $self->debugfh($cb_obj);
333 if( $self->connected ) {
334 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
335 $self->_dbh->disconnect;
343 if(my $dbh = $self->_dbh) {
344 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
345 $self->_sql_maker(undef);
346 return $self->_dbh(undef);
348 elsif($self->_conn_pid != $$) {
349 $self->_dbh->{InactiveDestroy} = 1;
350 $self->_sql_maker(undef);
351 return $self->_dbh(undef)
353 return ($dbh->FETCH('Active') && $dbh->ping);
359 sub ensure_connected {
362 unless ($self->connected) {
363 $self->_populate_dbh;
370 $self->ensure_connected;
376 unless ($self->_sql_maker) {
377 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
379 return $self->_sql_maker;
383 my ($self, $info_arg) = @_;
386 my $info = [ @$info_arg ]; # copy because we can alter it
387 my $last_info = $info->[-1];
388 if(ref $last_info eq 'HASH') {
390 if(my $on_connect_do = $last_info->{on_connect_do}) {
392 $self->on_connect_do($on_connect_do);
394 for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
395 if(my $opt_val = $last_info->{$sql_maker_opt}) {
397 $self->sql_maker->$sql_maker_opt($opt_val);
401 # remove our options hashref if it was there, to avoid confusing
402 # DBI in the case the user didn't use all 4 DBI options, as in:
403 # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ]
404 pop(@$info) if $used;
407 $self->_connect_info($info);
410 $self->_connect_info;
415 my @info = @{$self->_connect_info || []};
416 $self->_dbh($self->_connect(@info));
417 my $driver = $self->_dbh->{Driver}->{Name};
418 eval "require DBIx::Class::Storage::DBI::${driver}";
420 bless $self, "DBIx::Class::Storage::DBI::${driver}";
422 # if on-connect sql statements are given execute them
423 foreach my $sql_statement (@{$self->on_connect_do || []}) {
424 $self->_dbh->do($sql_statement);
427 $self->_conn_pid($$);
428 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
432 my ($self, @info) = @_;
434 $self->throw_exception("You failed to provide any connection info")
437 my ($old_connect_via, $dbh);
439 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
440 $old_connect_via = $DBI::connect_via;
441 $DBI::connect_via = 'connect';
444 if(ref $info[0] eq 'CODE') {
448 $dbh = DBI->connect(@info);
451 $DBI::connect_via = $old_connect_via if $old_connect_via;
453 $self->throw_exception("DBI Connection failed: $DBI::errstr")
461 Calls begin_work on the current dbh.
463 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
464 an entire code block to be executed transactionally.
470 $self->dbh->begin_work
471 if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
476 Issues a commit against the current dbh.
482 if ($self->{transaction_depth} == 0) {
483 $self->dbh->commit unless $self->dbh->{AutoCommit};
486 $self->dbh->commit if --$self->{transaction_depth} == 0;
492 Issues a rollback against the current dbh. A nested rollback will
493 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
494 which allows the rollback to propagate to the outermost transaction.
502 if ($self->{transaction_depth} == 0) {
503 $self->dbh->rollback unless $self->dbh->{AutoCommit};
506 --$self->{transaction_depth} == 0 ?
507 $self->dbh->rollback :
508 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
514 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
515 $error =~ /$exception_class/ and $self->throw_exception($error);
516 $self->{transaction_depth} = 0; # ensure that a failed rollback
517 $self->throw_exception($error); # resets the transaction depth
522 my ($self, $op, $extra_bind, $ident, @args) = @_;
523 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
524 unshift(@bind, @$extra_bind) if $extra_bind;
526 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
527 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
529 my $sth = $self->sth($sql,$op);
530 $self->throw_exception('no sth generated via sql (' . $self->_dbh->errstr . "): $sql") unless $sth;
531 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
534 $rv = $sth->execute(@bind)
535 or $self->throw_exception("Error executing '$sql': " . $sth->errstr);
537 $self->throw_exception("'$sql' did not generate a statement.");
539 return (wantarray ? ($rv, $sth, @bind) : $rv);
543 my ($self, $ident, $to_insert) = @_;
544 $self->throw_exception(
545 "Couldn't insert ".join(', ',
546 map "$_ => $to_insert->{$_}", keys %$to_insert
548 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
553 return shift->_execute('update' => [], @_);
557 return shift->_execute('delete' => [], @_);
561 my ($self, $ident, $select, $condition, $attrs) = @_;
562 my $order = $attrs->{order_by};
563 if (ref $condition eq 'SCALAR') {
564 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
566 if (exists $attrs->{group_by} || $attrs->{having}) {
568 group_by => $attrs->{group_by},
569 having => $attrs->{having},
570 ($order ? (order_by => $order) : ())
573 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
574 if ($attrs->{software_limit} ||
575 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
576 $attrs->{software_limit} = 1;
578 push @args, $attrs->{rows}, $attrs->{offset};
580 return $self->_execute(@args);
585 my ($ident, $select, $condition, $attrs) = @_;
586 return $self->cursor->new($self, \@_, $attrs);
589 # Need to call finish() to work round broken DBDs
593 my ($rv, $sth, @bind) = $self->_select(@_);
594 my @row = $sth->fetchrow_array;
600 my ($self, $sql) = @_;
601 # 3 is the if_active parameter which avoids active sth re-use
602 return $self->dbh->prepare_cached($sql, {}, 3);
605 =head2 columns_info_for
607 Returns database type info for a given table columns.
611 sub columns_info_for {
612 my ($self, $table) = @_;
614 if ($self->dbh->can('column_info')) {
616 my $old_raise_err = $self->dbh->{RaiseError};
617 my $old_print_err = $self->dbh->{PrintError};
618 $self->dbh->{RaiseError} = 1;
619 $self->dbh->{PrintError} = 0;
621 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
623 while ( my $info = $sth->fetchrow_hashref() ){
625 $column_info{data_type} = $info->{TYPE_NAME};
626 $column_info{size} = $info->{COLUMN_SIZE};
627 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
628 $column_info{default_value} = $info->{COLUMN_DEF};
630 $result{$info->{COLUMN_NAME}} = \%column_info;
633 $self->dbh->{RaiseError} = $old_raise_err;
634 $self->dbh->{PrintError} = $old_print_err;
635 return \%result if !$@;
639 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
641 my @columns = @{$sth->{NAME_lc}};
642 for my $i ( 0 .. $#columns ){
644 my $type_num = $sth->{TYPE}->[$i];
646 if(defined $type_num && $self->dbh->can('type_info')) {
647 my $type_info = $self->dbh->type_info($type_num);
648 $type_name = $type_info->{TYPE_NAME} if $type_info;
650 $column_info{data_type} = $type_name ? $type_name : $type_num;
651 $column_info{size} = $sth->{PRECISION}->[$i];
652 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
654 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
655 $column_info{data_type} = $1;
656 $column_info{size} = $2;
659 $result{$columns[$i]} = \%column_info;
666 my ($self, $row) = @_;
668 return $self->dbh->func('last_insert_rowid');
672 sub sqlt_type { shift->dbh->{Driver}->{Name} }
674 sub deployment_statements {
675 my ($self, $schema, $type, $sqltargs) = @_;
676 $type ||= $self->sqlt_type;
677 eval "use SQL::Translator";
678 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
679 eval "use SQL::Translator::Parser::DBIx::Class;";
680 $self->throw_exception($@) if $@;
681 eval "use SQL::Translator::Producer::${type};";
682 $self->throw_exception($@) if $@;
683 my $tr = SQL::Translator->new(%$sqltargs);
684 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
685 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
689 my ($self, $schema, $type, $sqltargs) = @_;
690 foreach my $statement ( $self->deployment_statements($schema, $type, $sqltargs) ) {
691 for ( split(";\n", $statement)) {
692 $self->debugfh->print("$_\n") if $self->debug;
693 $self->dbh->do($_) or warn "SQL was:\n $_";
698 sub DESTROY { shift->disconnect }
702 =head1 ENVIRONMENT VARIABLES
704 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
706 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
707 is produced (as when the L<debug> method is set).
709 If the value is of the form C<1=/path/name> then the trace output is
710 written to the file C</path/name>.
714 Matt S. Trout <mst@shadowcatsystems.co.uk>
716 Andy Grundman <andy@hybridized.org>
720 You may distribute this code under the same terms as Perl itself.