1 package DBIx::Class::Storage::DBI;
2 # -*- mode: cperl; cperl-indent-level: 2 -*-
4 use base 'DBIx::Class::Storage';
9 use SQL::Abstract::Limit;
10 use DBIx::Class::Storage::DBI::Cursor;
11 use DBIx::Class::Storage::Statistics;
13 use Carp::Clan qw/DBIx::Class/;
16 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
18 use base qw/SQL::Abstract::Limit/;
21 my ($self, $table, $fields, $where, $order, @rest) = @_;
22 $table = $self->_quote($table) unless ref($table);
23 @rest = (-1) unless defined $rest[0];
24 local $self->{having_bind} = [];
25 my ($sql, @ret) = $self->SUPER::select(
26 $table, $self->_recurse_fields($fields), $where, $order, @rest
28 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
34 $table = $self->_quote($table) unless ref($table);
35 $self->SUPER::insert($table, @_);
41 $table = $self->_quote($table) unless ref($table);
42 $self->SUPER::update($table, @_);
48 $table = $self->_quote($table) unless ref($table);
49 $self->SUPER::delete($table, @_);
55 return $_[1].$self->_order_by($_[2]);
57 return $self->SUPER::_emulate_limit(@_);
62 my ($self, $fields) = @_;
63 my $ref = ref $fields;
64 return $self->_quote($fields) unless $ref;
65 return $$fields if $ref eq 'SCALAR';
67 if ($ref eq 'ARRAY') {
68 return join(', ', map { $self->_recurse_fields($_) } @$fields);
69 } elsif ($ref eq 'HASH') {
70 foreach my $func (keys %$fields) {
71 return $self->_sqlcase($func)
72 .'( '.$self->_recurse_fields($fields->{$func}).' )';
81 if (ref $_[0] eq 'HASH') {
82 if (defined $_[0]->{group_by}) {
83 $ret = $self->_sqlcase(' group by ')
84 .$self->_recurse_fields($_[0]->{group_by});
86 if (defined $_[0]->{having}) {
88 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
89 push(@{$self->{having_bind}}, @extra);
90 $ret .= $self->_sqlcase(' having ').$frag;
92 if (defined $_[0]->{order_by}) {
93 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
95 } elsif(ref $_[0] eq 'SCALAR') {
96 $ret = $self->_sqlcase(' order by ').${ $_[0] };
98 $ret = $self->SUPER::_order_by(@_);
103 sub _order_directions {
104 my ($self, $order) = @_;
105 $order = $order->{order_by} if ref $order eq 'HASH';
106 return $self->SUPER::_order_directions($order);
110 my ($self, $from) = @_;
111 if (ref $from eq 'ARRAY') {
112 return $self->_recurse_from(@$from);
113 } elsif (ref $from eq 'HASH') {
114 return $self->_make_as($from);
116 return $from; # would love to quote here but _table ends up getting called
117 # twice during an ->select without a limit clause due to
118 # the way S::A::Limit->select works. should maybe consider
119 # bypassing this and doing S::A::select($self, ...) in
120 # our select method above. meantime, quoting shims have
121 # been added to select/insert/update/delete here
126 my ($self, $from, @join) = @_;
128 push(@sqlf, $self->_make_as($from));
129 foreach my $j (@join) {
132 # check whether a join type exists
133 my $join_clause = '';
134 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
135 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
137 $join_clause = ' JOIN ';
139 push(@sqlf, $join_clause);
141 if (ref $to eq 'ARRAY') {
142 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
144 push(@sqlf, $self->_make_as($to));
146 push(@sqlf, ' ON ', $self->_join_condition($on));
148 return join('', @sqlf);
152 my ($self, $from) = @_;
153 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
154 reverse each %{$self->_skip_options($from)});
158 my ($self, $hash) = @_;
160 $clean_hash->{$_} = $hash->{$_}
161 for grep {!/^-/} keys %$hash;
165 sub _join_condition {
166 my ($self, $cond) = @_;
167 if (ref $cond eq 'HASH') {
170 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
172 return $self->_recurse_where(\%j);
173 } elsif (ref $cond eq 'ARRAY') {
174 return join(' OR ', map { $self->_join_condition($_) } @$cond);
176 die "Can't handle this yet!";
181 my ($self, $label) = @_;
182 return '' unless defined $label;
183 return "*" if $label eq '*';
184 return $label unless $self->{quote_char};
185 if(ref $self->{quote_char} eq "ARRAY"){
186 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
187 if !defined $self->{name_sep};
188 my $sep = $self->{name_sep};
189 return join($self->{name_sep},
190 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
191 split(/\Q$sep\E/,$label));
193 return $self->SUPER::_quote($label);
199 $_[0] =~ s/SELECT (.*?) FROM/
200 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
201 $self->SUPER::_RowNum(@_);
204 # Accessor for setting limit dialect. This is useful
205 # for JDBC-bridge among others where the remote SQL-dialect cannot
206 # be determined by the name of the driver alone.
210 $self->{limit_dialect} = shift if @_;
211 return $self->{limit_dialect};
216 $self->{quote_char} = shift if @_;
217 return $self->{quote_char};
222 $self->{name_sep} = shift if @_;
223 return $self->{name_sep};
226 } # End of BEGIN block
228 use base qw/DBIx::Class/;
230 __PACKAGE__->load_components(qw/AccessorGroup/);
232 __PACKAGE__->mk_group_accessors('simple' =>
233 qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugobj
234 cursor on_connect_do transaction_depth/);
237 my $new = bless({}, ref $_[0] || $_[0]);
238 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
239 $new->transaction_depth(0);
241 $new->debugobj(new DBIx::Class::Storage::Statistics());
244 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
245 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
246 $fh = IO::File->new($1, 'w')
247 or $new->throw_exception("Cannot open trace file $1");
249 $fh = IO::File->new('>&STDERR');
251 $new->debugobj->debugfh($fh);
252 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
256 sub throw_exception {
257 my ($self, $msg) = @_;
263 DBIx::Class::Storage::DBI - DBI storage handler
269 This class represents the connection to the database
277 Connection information arrayref. Can either be the same arguments
278 one would pass to DBI->connect, or a code-reference which returns
279 a connected database handle. In either case, there is an optional
280 final element in the arrayref, which can hold a hashref of
281 connection-specific Storage::DBI options. These include
282 C<on_connect_do>, and the sql_maker options C<limit_dialect>,
283 C<quote_char>, and C<name_sep>. Examples:
285 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
286 ->connect_info(sub { DBI->connect(...) });
287 ->connect_info([ 'dbi:Pg:dbname=foo',
291 { quote_char => q{`}, name_sep => q{@} },
296 Executes the sql statements given as a listref on every db connect.
300 Causes SQL trace information to be emitted on the C<debugobj> object.
301 (or C<STDERR> if C<debugobj> has not specifically been set).
305 Set or retrieve the filehandle used for trace/debug output. This should be
306 an IO::Handle compatible ojbect (only the C<print> method is used. Initially
307 set to be STDERR - although see information on the
308 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
312 Sets or retrieves the object used for metric collection. Defaults to an instance
313 of L<DBIx::Class::Storage::Statistics> that is campatible with the original
314 method of using a coderef as a callback. See the aforementioned Statistics
315 class for more information.
319 Sets a callback to be executed each time a statement is run; takes a sub
320 reference. Callback is executed as $sub->($op, $info) where $op is
321 SELECT/INSERT/UPDATE/DELETE and $info is what would normally be printed.
323 See L<debugobj> for a better way.
329 if($self->debugobj()->can('callback')) {
330 $self->debugobj()->callback(shift());
337 if( $self->connected ) {
338 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
339 $self->_dbh->disconnect;
347 if(my $dbh = $self->_dbh) {
348 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
349 $self->_sql_maker(undef);
350 return $self->_dbh(undef);
352 elsif($self->_conn_pid != $$) {
353 $self->_dbh->{InactiveDestroy} = 1;
354 $self->_sql_maker(undef);
355 return $self->_dbh(undef)
357 return ($dbh->FETCH('Active') && $dbh->ping);
363 sub ensure_connected {
366 unless ($self->connected) {
367 $self->_populate_dbh;
373 Returns the dbh - a data base handle of class L<DBI>.
380 $self->ensure_connected;
384 sub _sql_maker_args {
387 return ( limit_dialect => $self->dbh );
392 unless ($self->_sql_maker) {
393 $self->_sql_maker(new DBIC::SQL::Abstract( $self->_sql_maker_args ));
395 return $self->_sql_maker;
399 my ($self, $info_arg) = @_;
402 my $info = [ @$info_arg ]; # copy because we can alter it
403 my $last_info = $info->[-1];
404 if(ref $last_info eq 'HASH') {
406 if(my $on_connect_do = $last_info->{on_connect_do}) {
408 $self->on_connect_do($on_connect_do);
410 for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
411 if(my $opt_val = $last_info->{$sql_maker_opt}) {
413 $self->sql_maker->$sql_maker_opt($opt_val);
417 # remove our options hashref if it was there, to avoid confusing
418 # DBI in the case the user didn't use all 4 DBI options, as in:
419 # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ]
420 pop(@$info) if $used;
423 $self->_connect_info($info);
426 $self->_connect_info;
431 my @info = @{$self->_connect_info || []};
432 $self->_dbh($self->_connect(@info));
433 my $dbh = $self->_dbh;
434 my $driver = $dbh->{Driver}->{Name};
435 if ( $driver eq 'ODBC' and $dbh->get_info(17) =~ m{^DB2/400} ) {
438 eval "require DBIx::Class::Storage::DBI::${driver}";
440 bless $self, "DBIx::Class::Storage::DBI::${driver}";
441 $self->_rebless() if $self->can('_rebless');
443 # if on-connect sql statements are given execute them
444 foreach my $sql_statement (@{$self->on_connect_do || []}) {
445 $self->debugobj->query_start($sql_statement) if $self->debug();
446 $self->_dbh->do($sql_statement);
447 $self->debugobj->query_end($sql_statement) if $self->debug();
450 $self->_conn_pid($$);
451 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
455 my ($self, @info) = @_;
457 $self->throw_exception("You failed to provide any connection info")
460 my ($old_connect_via, $dbh);
462 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
463 $old_connect_via = $DBI::connect_via;
464 $DBI::connect_via = 'connect';
468 if(ref $info[0] eq 'CODE') {
472 $dbh = DBI->connect(@info);
476 $DBI::connect_via = $old_connect_via if $old_connect_via;
479 $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
487 Calls begin_work on the current dbh.
489 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
490 an entire code block to be executed transactionally.
496 if ($self->{transaction_depth}++ == 0) {
497 my $dbh = $self->dbh;
498 if ($dbh->{AutoCommit}) {
499 $self->debugobj->txn_begin()
508 Issues a commit against the current dbh.
514 my $dbh = $self->dbh;
515 if ($self->{transaction_depth} == 0) {
516 unless ($dbh->{AutoCommit}) {
517 $self->debugobj->txn_commit()
523 if (--$self->{transaction_depth} == 0) {
524 $self->debugobj->txn_commit()
533 Issues a rollback against the current dbh. A nested rollback will
534 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
535 which allows the rollback to propagate to the outermost transaction.
543 my $dbh = $self->dbh;
544 if ($self->{transaction_depth} == 0) {
545 unless ($dbh->{AutoCommit}) {
546 $self->debugobj->txn_rollback()
552 if (--$self->{transaction_depth} == 0) {
553 $self->debugobj->txn_rollback()
558 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
565 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
566 $error =~ /$exception_class/ and $self->throw_exception($error);
567 $self->{transaction_depth} = 0; # ensure that a failed rollback
568 $self->throw_exception($error); # resets the transaction depth
573 my ($self, $op, $extra_bind, $ident, @args) = @_;
574 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
575 unshift(@bind, @$extra_bind) if $extra_bind;
577 my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
578 $self->debugobj->query_start($sql, @debug_bind);
580 my $sth = eval { $self->sth($sql,$op) };
583 $self->throw_exception(
584 'no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql"
587 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
591 $rv = eval { $sth->execute(@bind) };
594 $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
597 $self->throw_exception("'$sql' did not generate a statement.");
600 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
601 $self->debugobj->query_end($sql, @debug_bind);
603 return (wantarray ? ($rv, $sth, @bind) : $rv);
607 my ($self, $ident, $to_insert) = @_;
608 $self->throw_exception(
609 "Couldn't insert ".join(', ',
610 map "$_ => $to_insert->{$_}", keys %$to_insert
612 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
617 return shift->_execute('update' => [], @_);
621 return shift->_execute('delete' => [], @_);
625 my ($self, $ident, $select, $condition, $attrs) = @_;
626 my $order = $attrs->{order_by};
627 if (ref $condition eq 'SCALAR') {
628 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
630 if (exists $attrs->{group_by} || $attrs->{having}) {
632 group_by => $attrs->{group_by},
633 having => $attrs->{having},
634 ($order ? (order_by => $order) : ())
637 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
638 if ($attrs->{software_limit} ||
639 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
640 $attrs->{software_limit} = 1;
642 push @args, $attrs->{rows}, $attrs->{offset};
644 return $self->_execute(@args);
649 my ($ident, $select, $condition, $attrs) = @_;
650 return $self->cursor->new($self, \@_, $attrs);
653 # Need to call finish() to work round broken DBDs
657 my ($rv, $sth, @bind) = $self->_select(@_);
658 my @row = $sth->fetchrow_array;
664 my ($self, $sql) = @_;
665 # 3 is the if_active parameter which avoids active sth re-use
666 return $self->dbh->prepare_cached($sql, {}, 3);
669 =head2 columns_info_for
671 Returns database type info for a given table columns.
675 sub columns_info_for {
676 my ($self, $table) = @_;
678 my $dbh = $self->dbh;
680 if ($dbh->can('column_info')) {
682 my $old_raise_err = $dbh->{RaiseError};
683 my $old_print_err = $dbh->{PrintError};
684 $dbh->{RaiseError} = 1;
685 $dbh->{PrintError} = 0;
687 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
688 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
690 while ( my $info = $sth->fetchrow_hashref() ){
692 $column_info{data_type} = $info->{TYPE_NAME};
693 $column_info{size} = $info->{COLUMN_SIZE};
694 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
695 $column_info{default_value} = $info->{COLUMN_DEF};
696 my $col_name = $info->{COLUMN_NAME};
697 $col_name =~ s/^\"(.*)\"$/$1/;
699 $result{$col_name} = \%column_info;
702 $dbh->{RaiseError} = $old_raise_err;
703 $dbh->{PrintError} = $old_print_err;
704 return \%result if !$@;
708 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
710 my @columns = @{$sth->{NAME_lc}};
711 for my $i ( 0 .. $#columns ){
713 my $type_num = $sth->{TYPE}->[$i];
715 if(defined $type_num && $dbh->can('type_info')) {
716 my $type_info = $dbh->type_info($type_num);
717 $type_name = $type_info->{TYPE_NAME} if $type_info;
719 $column_info{data_type} = $type_name ? $type_name : $type_num;
720 $column_info{size} = $sth->{PRECISION}->[$i];
721 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
723 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
724 $column_info{data_type} = $1;
725 $column_info{size} = $2;
728 $result{$columns[$i]} = \%column_info;
735 my ($self, $row) = @_;
737 return $self->dbh->func('last_insert_rowid');
741 sub sqlt_type { shift->dbh->{Driver}->{Name} }
745 my ($self, $schema, $databases, $version, $dir, $sqltargs) = @_;
747 if(!$dir || !-d $dir)
749 warn "No directory given, using ./\n";
752 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
753 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
754 $version ||= $schema->VERSION || '1.x';
756 eval "use SQL::Translator";
757 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
759 my $sqlt = SQL::Translator->new({
763 foreach my $db (@$databases)
766 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
767 # $sqlt->parser_args({'DBIx::Class' => $schema);
768 $sqlt->data($schema);
769 $sqlt->producer($db);
772 my $filename = $schema->ddl_filename($db, $dir, $version);
775 $self->throw_exception("$filename already exists, skipping $db");
778 open($file, ">$filename")
779 or $self->throw_exception("Can't open $filename for writing ($!)");
780 my $output = $sqlt->translate;
782 # print join(":", keys %{$schema->source_registrations});
783 # print Dumper($sqlt->schema);
786 $self->throw_exception("Failed to translate to $db. (" . $sqlt->error . ")");
795 sub deployment_statements {
796 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
797 $type ||= $self->sqlt_type;
798 $version ||= $schema->VERSION || '1.x';
800 eval "use SQL::Translator";
803 eval "use SQL::Translator::Parser::DBIx::Class;";
804 $self->throw_exception($@) if $@;
805 eval "use SQL::Translator::Producer::${type};";
806 $self->throw_exception($@) if $@;
807 my $tr = SQL::Translator->new(%$sqltargs);
808 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
809 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
812 my $filename = $schema->ddl_filename($type, $dir, $version);
815 # $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs);
816 $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
820 open($file, "<$filename")
821 or $self->throw_exception("Can't open $filename ($!)");
825 return join('', @rows);
830 my ($self, $schema, $type, $sqltargs) = @_;
831 foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
832 for ( split(";\n", $statement)) {
833 next if($_ =~ /^--/);
835 # next if($_ =~ /^DROP/m);
836 next if($_ =~ /^BEGIN TRANSACTION/m);
837 next if($_ =~ /^COMMIT/m);
838 $self->debugobj->query_begin($_) if $self->debug;
839 $self->dbh->do($_) or warn "SQL was:\n $_";
840 $self->debugobj->query_end($_) if $self->debug;
845 sub datetime_parser {
847 return $self->{datetime_parser} ||= $self->build_datetime_parser(@_);
850 sub datetime_parser_type { "DateTime::Format::MySQL"; }
852 sub build_datetime_parser {
854 my $type = $self->datetime_parser_type(@_);
856 $self->throw_exception("Couldn't load ${type}: $@") if $@;
860 sub DESTROY { shift->disconnect }
864 =head1 ENVIRONMENT VARIABLES
866 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
868 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
869 is produced (as when the L<debug> method is set).
871 If the value is of the form C<1=/path/name> then the trace output is
872 written to the file C</path/name>.
874 This environment variable is checked when the storage object is first
875 created (when you call connect on your schema). So, run-time changes
876 to this environment variable will not take effect unless you also
877 re-connect on your schema.
881 Matt S. Trout <mst@shadowcatsystems.co.uk>
883 Andy Grundman <andy@hybridized.org>
887 You may distribute this code under the same terms as Perl itself.