1 package DBIx::Class::Storage::DBI;
6 use SQL::Abstract::Limit;
7 use DBIx::Class::Storage::DBI::Cursor;
9 use Carp::Clan qw/DBIx::Class/;
13 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
15 use base qw/SQL::Abstract::Limit/;
18 my ($self, $table, $fields, $where, $order, @rest) = @_;
19 @rest = (-1) unless defined $rest[0];
20 local $self->{having_bind} = [];
21 my ($sql, @ret) = $self->SUPER::select($table,
22 $self->_recurse_fields($fields), $where, $order, @rest);
23 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
29 return $_[1].$self->_order_by($_[2]);
31 return $self->SUPER::_emulate_limit(@_);
36 my ($self, $fields) = @_;
37 my $ref = ref $fields;
38 return $self->_quote($fields) unless $ref;
39 return $$fields if $ref eq 'SCALAR';
41 if ($ref eq 'ARRAY') {
42 return join(', ', map { $self->_recurse_fields($_) } @$fields);
43 } elsif ($ref eq 'HASH') {
44 foreach my $func (keys %$fields) {
45 return $self->_sqlcase($func)
46 .'( '.$self->_recurse_fields($fields->{$func}).' )';
55 if (ref $_[0] eq 'HASH') {
56 if (defined $_[0]->{group_by}) {
57 $ret = $self->_sqlcase(' group by ')
58 .$self->_recurse_fields($_[0]->{group_by});
60 if (defined $_[0]->{having}) {
62 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
63 push(@{$self->{having_bind}}, @extra);
64 $ret .= $self->_sqlcase(' having ').$frag;
66 if (defined $_[0]->{order_by}) {
67 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
70 $ret = $self->SUPER::_order_by(@_);
75 sub _order_directions {
76 my ($self, $order) = @_;
77 $order = $order->{order_by} if ref $order eq 'HASH';
78 return $self->SUPER::_order_directions($order);
82 my ($self, $from) = @_;
83 if (ref $from eq 'ARRAY') {
84 return $self->_recurse_from(@$from);
85 } elsif (ref $from eq 'HASH') {
86 return $self->_make_as($from);
93 my ($self, $from, @join) = @_;
95 push(@sqlf, $self->_make_as($from));
96 foreach my $j (@join) {
99 # check whether a join type exists
100 my $join_clause = '';
101 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
102 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
104 $join_clause = ' JOIN ';
106 push(@sqlf, $join_clause);
108 if (ref $to eq 'ARRAY') {
109 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
111 push(@sqlf, $self->_make_as($to));
113 push(@sqlf, ' ON ', $self->_join_condition($on));
115 return join('', @sqlf);
119 my ($self, $from) = @_;
120 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
121 reverse each %{$self->_skip_options($from)});
125 my ($self, $hash) = @_;
127 $clean_hash->{$_} = $hash->{$_}
128 for grep {!/^-/} keys %$hash;
132 sub _join_condition {
133 my ($self, $cond) = @_;
134 if (ref $cond eq 'HASH') {
136 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
137 return $self->_recurse_where(\%j);
138 } elsif (ref $cond eq 'ARRAY') {
139 return join(' OR ', map { $self->_join_condition($_) } @$cond);
141 die "Can't handle this yet!";
146 my ($self, $label) = @_;
147 return '' unless defined $label;
148 return "*" if $label eq '*';
149 return $label unless $self->{quote_char};
150 if(ref $self->{quote_char} eq "ARRAY"){
151 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
152 if !defined $self->{name_sep};
153 my $sep = $self->{name_sep};
154 return join($self->{name_sep},
155 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
156 split(/\Q$sep\E/,$label));
158 return $self->SUPER::_quote($label);
164 $_[0] =~ s/SELECT (.*?) FROM/
165 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
166 $self->SUPER::_RowNum(@_);
169 # Accessor for setting limit dialect. This is useful
170 # for JDBC-bridge among others where the remote SQL-dialect cannot
171 # be determined by the name of the driver alone.
175 $self->{limit_dialect} = shift if @_;
176 return $self->{limit_dialect};
181 $self->{quote_char} = shift if @_;
182 return $self->{quote_char};
187 $self->{name_sep} = shift if @_;
188 return $self->{name_sep};
194 package DBIx::Class::Storage::DBI::DebugCallback;
197 my ($self, $string) = @_;
198 $string =~ m/^(\w+)/;
199 ${$self}->($1, $string);
202 } # End of BEGIN block
204 use base qw/DBIx::Class/;
206 __PACKAGE__->load_components(qw/AccessorGroup/);
208 __PACKAGE__->mk_group_accessors('simple' =>
209 qw/connect_info _dbh _sql_maker _connection_pid debug debugfh cursor
210 on_connect_do transaction_depth/);
213 my $new = bless({}, ref $_[0] || $_[0]);
214 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
215 $new->transaction_depth(0);
216 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
217 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
218 $new->debugfh(IO::File->new($1, 'w')) || $new->throw_exception("Cannot open trace file $1");
220 $new->debugfh(IO::File->new('>&STDERR'));
222 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
226 sub throw_exception {
227 my ($self, $msg) = @_;
233 DBIx::Class::Storage::DBI - DBI storage handler
239 This class represents the connection to the database
247 Executes the sql statements given as a listref on every db connect.
251 Causes SQL trace information to be emitted on C<debugfh> filehandle
252 (or C<STDERR> if C<debugfh> has not specifically been set).
256 Sets or retrieves the filehandle used for trace/debug output. This
257 should be an IO::Handle compatible object (only the C<print> method is
258 used). Initially set to be STDERR - although see information on the
259 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
263 Sets a callback to be executed each time a statement is run; takes a sub
264 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
265 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
271 my ($self, $cb) = @_;
272 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
273 $self->debugfh($cb_obj);
279 if( $self->connected ) {
280 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
281 $self->_dbh->disconnect;
290 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
293 sub ensure_connected {
296 unless ($self->connected) {
297 $self->_populate_dbh;
305 if $self->_connection_pid && $self->_connection_pid != $$;
306 $self->ensure_connected;
312 unless ($self->_sql_maker) {
313 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
315 return $self->_sql_maker;
320 my @info = @{$self->connect_info || []};
321 $self->_dbh($self->_connect(@info));
322 my $driver = $self->_dbh->{Driver}->{Name};
323 eval "require DBIx::Class::Storage::DBI::${driver}";
325 bless $self, "DBIx::Class::Storage::DBI::${driver}";
327 # if on-connect sql statements are given execute them
328 foreach my $sql_statement (@{$self->on_connect_do || []}) {
329 $self->_dbh->do($sql_statement);
332 $self->_connection_pid($$);
336 my ($self, @info) = @_;
338 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
339 my $old_connect_via = $DBI::connect_via;
340 $DBI::connect_via = 'connect';
341 my $dbh = DBI->connect(@info);
342 $DBI::connect_via = $old_connect_via;
346 my $dbh = DBI->connect(@info);
347 $self->throw_exception("DBI Connection failed: $DBI::errstr")
354 Calls begin_work on the current dbh.
360 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
365 Issues a commit against the current dbh.
371 if ($self->{transaction_depth} == 0) {
372 $self->dbh->commit unless $self->dbh->{AutoCommit};
375 $self->dbh->commit if --$self->{transaction_depth} == 0;
381 Issues a rollback against the current dbh.
387 if ($self->{transaction_depth} == 0) {
388 $self->dbh->rollback unless $self->dbh->{AutoCommit};
391 --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;
396 my ($self, $op, $extra_bind, $ident, @args) = @_;
397 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
398 unshift(@bind, @$extra_bind) if $extra_bind;
400 my @debug_bind = map { defined $_ ? $_ : 'NULL' } @bind;
401 $self->debugfh->print("$sql: @debug_bind\n");
403 my $sth = $self->sth($sql,$op);
404 $self->throw_exception("no sth generated via sql: $sql") unless $sth;
405 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
408 $rv = $sth->execute(@bind);
410 $self->throw_exception("'$sql' did not generate a statement.");
412 return (wantarray ? ($rv, $sth, @bind) : $rv);
416 my ($self, $ident, $to_insert) = @_;
417 $self->throw_exception( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
418 unless ($self->_execute('insert' => [], $ident, $to_insert));
423 return shift->_execute('update' => [], @_);
427 return shift->_execute('delete' => [], @_);
431 my ($self, $ident, $select, $condition, $attrs) = @_;
432 my $order = $attrs->{order_by};
433 if (ref $condition eq 'SCALAR') {
434 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
436 if (exists $attrs->{group_by} || $attrs->{having}) {
437 $order = { group_by => $attrs->{group_by},
438 having => $attrs->{having},
439 ($order ? (order_by => $order) : ()) };
441 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
442 if ($attrs->{software_limit} ||
443 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
444 $attrs->{software_limit} = 1;
446 push @args, $attrs->{rows}, $attrs->{offset};
448 return $self->_execute(@args);
453 my ($ident, $select, $condition, $attrs) = @_;
454 return $self->cursor->new($self, \@_, $attrs);
457 # Need to call finish() to work round broken DBDs
461 my ($rv, $sth, @bind) = $self->_select(@_);
462 my @row = $sth->fetchrow_array;
468 my ($self, $sql) = @_;
469 # 3 is the if_active parameter which avoids active sth re-use
470 return $self->dbh->prepare_cached($sql, {}, 3);
473 =head2 columns_info_for
475 Returns database type info for a given table columns.
479 sub columns_info_for {
480 my ($self, $table) = @_;
482 if ( $self->dbh->can( 'column_info' ) ){
483 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
485 while ( my $info = $sth->fetchrow_hashref() ){
487 $column_info{data_type} = $info->{TYPE_NAME};
488 $column_info{size} = $info->{COLUMN_SIZE};
489 $column_info{is_nullable} = $info->{NULLABLE};
490 $result{$info->{COLUMN_NAME}} = \%column_info;
493 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
495 my @columns = @{$sth->{NAME}};
496 for my $i ( 0 .. $#columns ){
497 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
504 my ($self, $row) = @_;
506 return $self->dbh->func('last_insert_rowid');
512 my $dsn = $self->connect_info->[0];
513 $dsn =~ /^dbi:(.*?)\d*:/;
517 sub deployment_statements {
518 my ($self, $schema, $type) = @_;
519 $type ||= $self->sqlt_type;
520 eval "use SQL::Translator";
521 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
522 eval "use SQL::Translator::Parser::DBIx::Class;";
523 $self->throw_exception($@) if $@;
524 eval "use SQL::Translator::Producer::${type};";
525 $self->throw_exception($@) if $@;
526 my $tr = SQL::Translator->new();
527 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
528 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
532 my ($self, $schema, $type) = @_;
533 $self->dbh->do($_) for split(";\n", $self->deployment_statements($schema, $type));
536 sub DESTROY { shift->disconnect }
540 =head1 ENVIRONMENT VARIABLES
542 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
544 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
545 is produced (as when the L<debug> method is set).
547 If the value is of the form C<1=/path/name> then the trace output is
548 written to the file C</path/name>.
552 Matt S. Trout <mst@shadowcatsystems.co.uk>
554 Andy Grundman <andy@hybridized.org>
558 You may distribute this code under the same terms as Perl itself.