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;
12 use Storable 'dclone';
13 use Carp::Clan qw/DBIx::Class/;
17 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
19 use base qw/SQL::Abstract::Limit/;
22 my ($self, $table, $fields, $where, $order, @rest) = @_;
23 $table = $self->_quote($table) unless ref($table);
24 @rest = (-1) unless defined $rest[0];
25 local $self->{having_bind} = [];
26 my ($sql, @ret) = $self->SUPER::select(
27 $table, $self->_recurse_fields($fields), $where, $order, @rest
29 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
35 $table = $self->_quote($table) unless ref($table);
36 $self->SUPER::insert($table, @_);
42 $table = $self->_quote($table) unless ref($table);
43 $self->SUPER::update($table, @_);
49 $table = $self->_quote($table) unless ref($table);
50 $self->SUPER::delete($table, @_);
56 return $_[1].$self->_order_by($_[2]);
58 return $self->SUPER::_emulate_limit(@_);
63 my ($self, $fields) = @_;
64 my $ref = ref $fields;
65 return $self->_quote($fields) unless $ref;
66 return $$fields if $ref eq 'SCALAR';
68 if ($ref eq 'ARRAY') {
69 return join(', ', map { $self->_recurse_fields($_) } @$fields);
70 } elsif ($ref eq 'HASH') {
71 foreach my $func (keys %$fields) {
72 return $self->_sqlcase($func)
73 .'( '.$self->_recurse_fields($fields->{$func}).' )';
82 if (ref $_[0] eq 'HASH') {
83 if (defined $_[0]->{group_by}) {
84 $ret = $self->_sqlcase(' group by ')
85 .$self->_recurse_fields($_[0]->{group_by});
87 if (defined $_[0]->{having}) {
89 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
90 push(@{$self->{having_bind}}, @extra);
91 $ret .= $self->_sqlcase(' having ').$frag;
93 if (defined $_[0]->{order_by}) {
94 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
96 } elsif(ref $_[0] eq 'SCALAR') {
97 $ret = $self->_sqlcase(' order by ').${ $_[0] };
99 $ret = $self->SUPER::_order_by(@_);
104 sub _order_directions {
105 my ($self, $order) = @_;
106 $order = $order->{order_by} if ref $order eq 'HASH';
107 return $self->SUPER::_order_directions($order);
111 my ($self, $from) = @_;
112 if (ref $from eq 'ARRAY') {
113 return $self->_recurse_from(@$from);
114 } elsif (ref $from eq 'HASH') {
115 return $self->_make_as($from);
117 return $from; # would love to quote here but _table ends up getting called
118 # twice during an ->select without a limit clause due to
119 # the way S::A::Limit->select works. should maybe consider
120 # bypassing this and doing S::A::select($self, ...) in
121 # our select method above. meantime, quoting shims have
122 # been added to select/insert/update/delete here
127 my ($self, $from, @join) = @_;
129 push(@sqlf, $self->_make_as($from));
130 foreach my $j (@join) {
133 # check whether a join type exists
134 my $join_clause = '';
135 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
136 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
138 $join_clause = ' JOIN ';
140 push(@sqlf, $join_clause);
142 if (ref $to eq 'ARRAY') {
143 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
145 push(@sqlf, $self->_make_as($to));
147 push(@sqlf, ' ON ', $self->_join_condition($on));
149 return join('', @sqlf);
153 my ($self, $from) = @_;
154 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
155 reverse each %{$self->_skip_options($from)});
159 my ($self, $hash) = @_;
161 $clean_hash->{$_} = $hash->{$_}
162 for grep {!/^-/} keys %$hash;
166 sub _join_condition {
167 my ($self, $cond) = @_;
168 if (ref $cond eq 'HASH') {
171 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
173 return $self->_recurse_where(\%j);
174 } elsif (ref $cond eq 'ARRAY') {
175 return join(' OR ', map { $self->_join_condition($_) } @$cond);
177 die "Can't handle this yet!";
182 my ($self, $label) = @_;
183 return '' unless defined $label;
184 return "*" if $label eq '*';
185 return $label unless $self->{quote_char};
186 if(ref $self->{quote_char} eq "ARRAY"){
187 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
188 if !defined $self->{name_sep};
189 my $sep = $self->{name_sep};
190 return join($self->{name_sep},
191 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
192 split(/\Q$sep\E/,$label));
194 return $self->SUPER::_quote($label);
200 $_[0] =~ s/SELECT (.*?) FROM/
201 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
202 $self->SUPER::_RowNum(@_);
205 # Accessor for setting limit dialect. This is useful
206 # for JDBC-bridge among others where the remote SQL-dialect cannot
207 # be determined by the name of the driver alone.
211 $self->{limit_dialect} = shift if @_;
212 return $self->{limit_dialect};
217 $self->{quote_char} = shift if @_;
218 return $self->{quote_char};
223 $self->{name_sep} = shift if @_;
224 return $self->{name_sep};
230 package DBIx::Class::Storage::DBI::DebugCallback;
233 my ($self, $string) = @_;
234 $string =~ m/^(\w+)/;
235 ${$self}->($1, $string);
238 } # End of BEGIN block
240 use base qw/DBIx::Class/;
242 __PACKAGE__->load_components(qw/AccessorGroup/);
244 __PACKAGE__->mk_group_accessors('simple' =>
245 qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
246 cursor on_connect_do transaction_depth/);
249 my $new = bless({}, ref $_[0] || $_[0]);
250 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
251 $new->transaction_depth(0);
252 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
253 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
254 $new->debugfh(IO::File->new($1, 'w'))
255 or $new->throw_exception("Cannot open trace file $1");
257 $new->debugfh(IO::File->new('>&STDERR'));
259 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
263 sub throw_exception {
264 my ($self, $msg) = @_;
270 DBIx::Class::Storage::DBI - DBI storage handler
276 This class represents the connection to the database
284 Connection information arrayref. Can either be the same arguments
285 one would pass to DBI->connect, or a code-reference which returns
286 a connected database handle. In either case, there is an optional
287 final element in the arrayref, which can hold a hashref of
288 connection-specific Storage::DBI options. These include
289 C<on_connect_do>, and the sql_maker options C<limit_dialect>,
290 C<quote_char>, and C<name_sep>. Examples:
292 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
293 ->connect_info(sub { DBI->connect(...) });
294 ->connect_info([ 'dbi:Pg:dbname=foo',
298 { quote_char => q{`}, name_sep => q{@} },
303 Executes the sql statements given as a listref on every db connect.
307 Causes SQL trace information to be emitted on C<debugfh> filehandle
308 (or C<STDERR> if C<debugfh> has not specifically been set).
312 Sets or retrieves the filehandle used for trace/debug output. This
313 should be an IO::Handle compatible object (only the C<print> method is
314 used). Initially set to be STDERR - although see information on the
315 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
319 Sets a callback to be executed each time a statement is run; takes a sub
320 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
321 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
327 my ($self, $cb) = @_;
328 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
329 $self->debugfh($cb_obj);
335 if( $self->connected ) {
336 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
337 $self->_dbh->disconnect;
345 if(my $dbh = $self->_dbh) {
346 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
347 $self->_sql_maker(undef);
348 return $self->_dbh(undef);
350 elsif($self->_conn_pid != $$) {
351 $self->_dbh->{InactiveDestroy} = 1;
352 $self->_sql_maker(undef);
353 return $self->_dbh(undef)
355 return ($dbh->FETCH('Active') && $dbh->ping);
361 sub ensure_connected {
364 unless ($self->connected) {
365 $self->_populate_dbh;
371 Returns the dbh - a data base handle of class L<DBI>.
378 $self->ensure_connected;
384 unless ($self->_sql_maker) {
385 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
387 return $self->_sql_maker;
391 my ($self, $info_arg) = @_;
394 my $info = [ @$info_arg ]; # copy because we can alter it
395 my $last_info = $info->[-1];
396 if(ref $last_info eq 'HASH') {
398 if(my $on_connect_do = $last_info->{on_connect_do}) {
400 $self->on_connect_do($on_connect_do);
402 for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
403 if(my $opt_val = $last_info->{$sql_maker_opt}) {
405 $self->sql_maker->$sql_maker_opt($opt_val);
409 # remove our options hashref if it was there, to avoid confusing
410 # DBI in the case the user didn't use all 4 DBI options, as in:
411 # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ]
412 pop(@$info) if $used;
415 $self->_connect_info($info);
418 $self->_connect_info;
423 my @info = @{$self->_connect_info || []};
424 $self->_dbh($self->_connect(@info));
425 my $dbh = $self->_dbh;
426 my $driver = $dbh->{Driver}->{Name};
427 if ( $driver eq 'ODBC' and $dbh->get_info(17) =~ m{^DB2/400} ) {
430 eval "require DBIx::Class::Storage::DBI::${driver}";
432 bless $self, "DBIx::Class::Storage::DBI::${driver}";
434 # if on-connect sql statements are given execute them
435 foreach my $sql_statement (@{$self->on_connect_do || []}) {
436 $self->_dbh->do($sql_statement);
439 $self->_conn_pid($$);
440 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
444 my ($self, @info) = @_;
446 $self->throw_exception("You failed to provide any connection info")
449 my ($old_connect_via, $dbh);
451 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
452 $old_connect_via = $DBI::connect_via;
453 $DBI::connect_via = 'connect';
457 if(ref $info[0] eq 'CODE') {
461 $dbh = DBI->connect(@info);
465 $DBI::connect_via = $old_connect_via if $old_connect_via;
468 $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
476 Calls begin_work on the current dbh.
478 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
479 an entire code block to be executed transactionally.
485 if ($self->{transaction_depth}++ == 0) {
486 my $dbh = $self->dbh;
487 if ($dbh->{AutoCommit}) {
488 $self->debugfh->print("BEGIN WORK\n")
497 Issues a commit against the current dbh.
503 if ($self->{transaction_depth} == 0) {
504 my $dbh = $self->dbh;
505 unless ($dbh->{AutoCommit}) {
506 $self->debugfh->print("COMMIT\n")
512 if (--$self->{transaction_depth} == 0) {
513 $self->debugfh->print("COMMIT\n")
522 Issues a rollback against the current dbh. A nested rollback will
523 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
524 which allows the rollback to propagate to the outermost transaction.
532 if ($self->{transaction_depth} == 0) {
533 my $dbh = $self->dbh;
534 unless ($dbh->{AutoCommit}) {
535 $self->debugfh->print("ROLLBACK\n")
541 if (--$self->{transaction_depth} == 0) {
542 $self->debugfh->print("ROLLBACK\n")
544 $self->dbh->rollback;
547 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
554 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
555 $error =~ /$exception_class/ and $self->throw_exception($error);
556 $self->{transaction_depth} = 0; # ensure that a failed rollback
557 $self->throw_exception($error); # resets the transaction depth
562 my ($self, $op, $extra_bind, $ident, @args) = @_;
563 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
564 unshift(@bind, @$extra_bind) if $extra_bind;
566 my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
567 $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
569 my $sth = eval { $self->sth($sql,$op) };
572 $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql");
575 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
578 $rv = eval { $sth->execute(@bind) };
581 $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
584 $self->throw_exception("'$sql' did not generate a statement.");
586 return (wantarray ? ($rv, $sth, @bind) : $rv);
590 my ($self, $ident, $to_insert) = @_;
591 $self->throw_exception(
592 "Couldn't insert ".join(', ',
593 map "$_ => $to_insert->{$_}", keys %$to_insert
595 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
600 return shift->_execute('update' => [], @_);
604 return shift->_execute('delete' => [], @_);
608 my ($self, $ident, $select, $condition, $attrs) = @_;
609 my $order = $attrs->{order_by};
610 if (ref $condition eq 'SCALAR') {
611 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
613 if (exists $attrs->{group_by} || $attrs->{having}) {
615 group_by => $attrs->{group_by},
616 having => $attrs->{having},
617 ($order ? (order_by => $order) : ())
620 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
621 if ($attrs->{software_limit} ||
622 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
623 $attrs->{software_limit} = 1;
625 push @args, $attrs->{rows}, $attrs->{offset};
627 return $self->_execute(@args);
632 my ($ident, $select, $condition, $attrs) = @_;
633 return $self->cursor->new($self, \@_, $attrs);
636 # Need to call finish() to work round broken DBDs
640 my ($rv, $sth, @bind) = $self->_select(@_);
641 my @row = $sth->fetchrow_array;
647 my ($self, $sql) = @_;
648 # 3 is the if_active parameter which avoids active sth re-use
649 return $self->dbh->prepare_cached($sql, {}, 3);
652 =head2 columns_info_for
654 Returns database type info for a given table columns.
658 sub columns_info_for {
659 my ($self, $table) = @_;
661 my $dbh = $self->dbh;
663 if ($dbh->can('column_info')) {
665 my $old_raise_err = $dbh->{RaiseError};
666 my $old_print_err = $dbh->{PrintError};
667 $dbh->{RaiseError} = 1;
668 $dbh->{PrintError} = 0;
670 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
671 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
673 while ( my $info = $sth->fetchrow_hashref() ){
675 $column_info{data_type} = $info->{TYPE_NAME};
676 $column_info{size} = $info->{COLUMN_SIZE};
677 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
678 $column_info{default_value} = $info->{COLUMN_DEF};
680 $result{$info->{COLUMN_NAME}} = \%column_info;
683 $dbh->{RaiseError} = $old_raise_err;
684 $dbh->{PrintError} = $old_print_err;
685 return \%result if !$@;
689 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
691 my @columns = @{$sth->{NAME_lc}};
692 for my $i ( 0 .. $#columns ){
694 my $type_num = $sth->{TYPE}->[$i];
696 if(defined $type_num && $dbh->can('type_info')) {
697 my $type_info = $dbh->type_info($type_num);
698 $type_name = $type_info->{TYPE_NAME} if $type_info;
700 $column_info{data_type} = $type_name ? $type_name : $type_num;
701 $column_info{size} = $sth->{PRECISION}->[$i];
702 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
704 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
705 $column_info{data_type} = $1;
706 $column_info{size} = $2;
709 $result{$columns[$i]} = \%column_info;
716 my ($self, $row) = @_;
718 return $self->dbh->func('last_insert_rowid');
722 sub sqlt_type { shift->dbh->{Driver}->{Name} }
726 my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
728 if(!$dir || !-d $dir)
730 warn "No directory given, using ./\n";
733 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
734 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
735 $version ||= $schema->VERSION || '1.x';
737 eval "use SQL::Translator";
738 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
740 my $sqlt = SQL::Translator->new({
744 foreach my $db (@$databases)
747 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
748 # $sqlt->parser_args({'DBIx::Class' => $schema);
749 $sqlt->data($schema);
750 $sqlt->producer($db);
753 my $filename = $schema->ddl_filename($dir, $db, $version);
756 warn("$filename already exists, skipping $db");
759 open($file, ">$filename")
760 or warn("Can't open $filename for writing ($!)"), next;
761 my $output = $sqlt->translate;
764 warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
772 eval "use SQL::Translator::Diff";
773 warn("Can't diff versions without SQL::Translator::Diff: $@"), next if $@;
775 my $prefilename = $schema->ddl_filename($dir, $db, $preversion);
776 print "Previous version $prefilename\n";
779 warn("No previous schema file found ($prefilename)");
782 #### We need to reparse the SQLite file we just wrote, so that
783 ## Diff doesnt get all confoosed, and Diff is *very* confused.
784 ## FIXME: rip Diff to pieces!
785 # my $target_schema = $sqlt->schema;
786 # unless ( $target_schema->name ) {
787 # $target_schema->name( $filename );
789 my $sqlt = SQL::Translator->new();
790 $sqlt->parser("SQL::Translator::Parser::$db");
791 $sqlt->filename($filename);
792 $sqlt->translate() or warn("Failed to parse $filename as $db, (" .
793 $sqlt->error . ")"), next;
794 my $target_schema = $sqlt->schema;
795 unless ( $target_schema->name ) {
796 $target_schema->name( $filename );
800 my $psqlt = SQL::Translator->new();
801 $psqlt->parser("SQL::Translator::Parser::$db");
802 $psqlt->filename($prefilename);
803 $psqlt->translate() or warn("Failed to parse $filename as $db, (" .
804 $sqlt->error . ")"), next ;
805 my $source_schema = $psqlt->schema;
806 unless ( $source_schema->name ) {
807 $source_schema->name( $prefilename );
810 my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
814 my $difffile = $filename;
815 $difffile =~ s/$version/${preversion}-${version}/;
818 warn("$difffile already exists, skipping");
821 open $file, ">$difffile" or
822 warn("Can't write to $difffile ($!)"), next;
830 sub deployment_statements {
831 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
832 $type ||= $self->sqlt_type;
833 $version ||= $schema->VERSION || '1.x';
835 eval "use SQL::Translator";
838 eval "use SQL::Translator::Parser::DBIx::Class;";
839 $self->throw_exception($@) if $@;
840 eval "use SQL::Translator::Producer::${type};";
841 $self->throw_exception($@) if $@;
842 my $tr = SQL::Translator->new(%$sqltargs);
843 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
844 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
847 my $filename = $schema->ddl_filename($dir, $type, $version);
850 # $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs);
851 $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
855 open($file, "<$filename")
856 or $self->throw_exception("Can't open $filename ($!)");
860 return join('', @rows);
865 my ($self, $schema, $type, $sqltargs) = @_;
866 foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
867 for ( split(";\n", $statement)) {
868 next if($_ =~ /^--/);
870 # next if($_ =~ /^DROP/m);
871 next if($_ =~ /^BEGIN TRANSACTION/m);
872 next if($_ =~ /^COMMIT/m);
873 $self->debugfh->print("$_\n") if $self->debug;
874 $self->dbh->do($_) or warn "SQL was:\n $_";
879 sub DESTROY { shift->disconnect }
883 =head1 ENVIRONMENT VARIABLES
885 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
887 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
888 is produced (as when the L<debug> method is set).
890 If the value is of the form C<1=/path/name> then the trace output is
891 written to the file C</path/name>.
895 Matt S. Trout <mst@shadowcatsystems.co.uk>
897 Andy Grundman <andy@hybridized.org>
899 Jess Robinson <castaway@desert-island.demon.co.uk>
903 You may distribute this code under the same terms as Perl itself.