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});
72 $ret = $self->SUPER::_order_by(@_);
77 sub _order_directions {
78 my ($self, $order) = @_;
79 $order = $order->{order_by} if ref $order eq 'HASH';
80 return $self->SUPER::_order_directions($order);
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);
95 my ($self, $from, @join) = @_;
97 push(@sqlf, $self->_make_as($from));
98 foreach my $j (@join) {
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 ';
106 $join_clause = ' JOIN ';
108 push(@sqlf, $join_clause);
110 if (ref $to eq 'ARRAY') {
111 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
113 push(@sqlf, $self->_make_as($to));
115 push(@sqlf, ' ON ', $self->_join_condition($on));
117 return join('', @sqlf);
121 my ($self, $from) = @_;
122 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
123 reverse each %{$self->_skip_options($from)});
127 my ($self, $hash) = @_;
129 $clean_hash->{$_} = $hash->{$_}
130 for grep {!/^-/} keys %$hash;
134 sub _join_condition {
135 my ($self, $cond) = @_;
136 if (ref $cond eq 'HASH') {
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);
143 die "Can't handle this yet!";
148 my ($self, $label) = @_;
149 return '' unless defined $label;
150 return "*" if $label eq '*';
151 return $label unless $self->{quote_char};
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));
160 return $self->SUPER::_quote($label);
166 $_[0] =~ s/SELECT (.*?) FROM/
167 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
168 $self->SUPER::_RowNum(@_);
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.
177 $self->{limit_dialect} = shift if @_;
178 return $self->{limit_dialect};
183 $self->{quote_char} = shift if @_;
184 return $self->{quote_char};
189 $self->{name_sep} = shift if @_;
190 return $self->{name_sep};
196 package DBIx::Class::Storage::DBI::DebugCallback;
199 my ($self, $string) = @_;
200 $string =~ m/^(\w+)/;
201 ${$self}->($1, $string);
204 } # End of BEGIN block
206 use base qw/DBIx::Class/;
208 __PACKAGE__->load_components(qw/AccessorGroup/);
210 __PACKAGE__->mk_group_accessors('simple' =>
211 qw/connect_info _dbh _sql_maker _connection_pid debug debugfh cursor
212 on_connect_do transaction_depth/);
215 my $new = bless({}, ref $_[0] || $_[0]);
216 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
217 $new->transaction_depth(0);
218 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
219 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
220 $new->debugfh(IO::File->new($1, 'w')) || $new->throw_exception("Cannot open trace file $1");
222 $new->debugfh(IO::File->new('>&STDERR'));
224 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
228 sub throw_exception {
229 my ($self, $msg) = @_;
235 DBIx::Class::Storage::DBI - DBI storage handler
241 This class represents the connection to the database
249 Executes the sql statements given as a listref on every db connect.
253 Causes SQL trace information to be emitted on C<debugfh> filehandle
254 (or C<STDERR> if C<debugfh> has not specifically been set).
258 Sets or retrieves the filehandle used for trace/debug output. This
259 should be an IO::Handle compatible object (only the C<print> method is
260 used). Initially set to be STDERR - although see information on the
261 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
265 Sets a callback to be executed each time a statement is run; takes a sub
266 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
267 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
273 my ($self, $cb) = @_;
274 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
275 $self->debugfh($cb_obj);
281 if( $self->connected ) {
282 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
283 $self->_dbh->disconnect;
292 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
295 sub ensure_connected {
298 unless ($self->connected) {
299 $self->_populate_dbh;
307 if $self->_connection_pid && $self->_connection_pid != $$;
308 $self->ensure_connected;
314 unless ($self->_sql_maker) {
315 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
317 return $self->_sql_maker;
322 my @info = @{$self->connect_info || []};
323 $self->_dbh($self->_connect(@info));
324 my $driver = $self->_dbh->{Driver}->{Name};
325 eval "require DBIx::Class::Storage::DBI::${driver}";
327 bless $self, "DBIx::Class::Storage::DBI::${driver}";
329 # if on-connect sql statements are given execute them
330 foreach my $sql_statement (@{$self->on_connect_do || []}) {
331 $self->_dbh->do($sql_statement);
334 $self->_connection_pid($$);
338 my ($self, @info) = @_;
340 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
341 my $old_connect_via = $DBI::connect_via;
342 $DBI::connect_via = 'connect';
343 my $dbh = DBI->connect(@info);
344 $DBI::connect_via = $old_connect_via;
348 my $dbh = DBI->connect(@info);
349 $self->throw_exception("DBI Connection failed: $DBI::errstr")
356 Calls begin_work on the current dbh.
362 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
367 Issues a commit against the current dbh.
373 if ($self->{transaction_depth} == 0) {
374 $self->dbh->commit unless $self->dbh->{AutoCommit};
377 $self->dbh->commit if --$self->{transaction_depth} == 0;
383 Issues a rollback against the current dbh.
391 if ($self->{transaction_depth} == 0) {
392 $self->dbh->rollback unless $self->dbh->{AutoCommit};
395 --$self->{transaction_depth} == 0 ?
396 $self->dbh->rollback :
397 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
403 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
404 $error =~ /$exception_class/ and $self->throw_exception($error);
405 $self->{transaction_depth} = 0; # ensure that a failed rollback
406 $self->throw_exception($error); # resets the transaction depth
411 my ($self, $op, $extra_bind, $ident, @args) = @_;
412 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
413 unshift(@bind, @$extra_bind) if $extra_bind;
415 my @debug_bind = map { defined $_ ? $_ : 'NULL' } @bind;
416 $self->debugfh->print("$sql: @debug_bind\n");
418 my $sth = $self->sth($sql,$op);
419 $self->throw_exception("no sth generated via sql: $sql") unless $sth;
420 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
423 $rv = $sth->execute(@bind);
425 $self->throw_exception("'$sql' did not generate a statement.");
427 return (wantarray ? ($rv, $sth, @bind) : $rv);
431 my ($self, $ident, $to_insert) = @_;
432 $self->throw_exception( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
433 unless ($self->_execute('insert' => [], $ident, $to_insert));
438 return shift->_execute('update' => [], @_);
442 return shift->_execute('delete' => [], @_);
446 my ($self, $ident, $select, $condition, $attrs) = @_;
447 my $order = $attrs->{order_by};
448 if (ref $condition eq 'SCALAR') {
449 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
451 if (exists $attrs->{group_by} || $attrs->{having}) {
452 $order = { group_by => $attrs->{group_by},
453 having => $attrs->{having},
454 ($order ? (order_by => $order) : ()) };
456 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
457 if ($attrs->{software_limit} ||
458 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
459 $attrs->{software_limit} = 1;
461 push @args, $attrs->{rows}, $attrs->{offset};
463 return $self->_execute(@args);
468 my ($ident, $select, $condition, $attrs) = @_;
469 return $self->cursor->new($self, \@_, $attrs);
472 # Need to call finish() to work round broken DBDs
476 my ($rv, $sth, @bind) = $self->_select(@_);
477 my @row = $sth->fetchrow_array;
483 my ($self, $sql) = @_;
484 # 3 is the if_active parameter which avoids active sth re-use
485 return $self->dbh->prepare_cached($sql, {}, 3);
488 =head2 columns_info_for
490 Returns database type info for a given table columns.
494 sub columns_info_for {
495 my ($self, $table) = @_;
497 if ( $self->dbh->can( 'column_info' ) ){
498 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
500 while ( my $info = $sth->fetchrow_hashref() ){
502 $column_info{data_type} = $info->{TYPE_NAME};
503 $column_info{size} = $info->{COLUMN_SIZE};
504 $column_info{is_nullable} = $info->{NULLABLE};
505 $result{$info->{COLUMN_NAME}} = \%column_info;
508 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
510 my @columns = @{$sth->{NAME}};
511 for my $i ( 0 .. $#columns ){
512 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
519 my ($self, $row) = @_;
521 return $self->dbh->func('last_insert_rowid');
527 my $dsn = $self->connect_info->[0];
528 $dsn =~ /^dbi:(.*?)\d*:/;
532 sub deployment_statements {
533 my ($self, $schema, $type) = @_;
534 $type ||= $self->sqlt_type;
535 eval "use SQL::Translator";
536 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
537 eval "use SQL::Translator::Parser::DBIx::Class;";
538 $self->throw_exception($@) if $@;
539 eval "use SQL::Translator::Producer::${type};";
540 $self->throw_exception($@) if $@;
541 my $tr = SQL::Translator->new();
542 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
543 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
547 my ($self, $schema, $type) = @_;
548 foreach(split(";\n", $self->deployment_statements($schema, $type))) {
549 $self->dbh->do($_) or warn "SQL was:\n $_";
553 sub DESTROY { shift->disconnect }
557 =head1 ENVIRONMENT VARIABLES
559 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
561 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
562 is produced (as when the L<debug> method is set).
564 If the value is of the form C<1=/path/name> then the trace output is
565 written to the file C</path/name>.
569 Matt S. Trout <mst@shadowcatsystems.co.uk>
571 Andy Grundman <andy@hybridized.org>
575 You may distribute this code under the same terms as Perl itself.