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 die "LIMIT 0 Does Not Compute" if $rest[0] == 0;
25 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
26 local $self->{having_bind} = [];
27 my ($sql, @ret) = $self->SUPER::select(
28 $table, $self->_recurse_fields($fields), $where, $order, @rest
30 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
36 $table = $self->_quote($table) unless ref($table);
37 $self->SUPER::insert($table, @_);
43 $table = $self->_quote($table) unless ref($table);
44 $self->SUPER::update($table, @_);
50 $table = $self->_quote($table) unless ref($table);
51 $self->SUPER::delete($table, @_);
57 return $_[1].$self->_order_by($_[2]);
59 return $self->SUPER::_emulate_limit(@_);
64 my ($self, $fields) = @_;
65 my $ref = ref $fields;
66 return $self->_quote($fields) unless $ref;
67 return $$fields if $ref eq 'SCALAR';
69 if ($ref eq 'ARRAY') {
70 return join(', ', map { $self->_recurse_fields($_) } @$fields);
71 } elsif ($ref eq 'HASH') {
72 foreach my $func (keys %$fields) {
73 return $self->_sqlcase($func)
74 .'( '.$self->_recurse_fields($fields->{$func}).' )';
83 if (ref $_[0] eq 'HASH') {
84 if (defined $_[0]->{group_by}) {
85 $ret = $self->_sqlcase(' group by ')
86 .$self->_recurse_fields($_[0]->{group_by});
88 if (defined $_[0]->{having}) {
90 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
91 push(@{$self->{having_bind}}, @extra);
92 $ret .= $self->_sqlcase(' having ').$frag;
94 if (defined $_[0]->{order_by}) {
95 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
97 } elsif(ref $_[0] eq 'SCALAR') {
98 $ret = $self->_sqlcase(' order by ').${ $_[0] };
100 $ret = $self->SUPER::_order_by(@_);
105 sub _order_directions {
106 my ($self, $order) = @_;
107 $order = $order->{order_by} if ref $order eq 'HASH';
108 return $self->SUPER::_order_directions($order);
112 my ($self, $from) = @_;
113 if (ref $from eq 'ARRAY') {
114 return $self->_recurse_from(@$from);
115 } elsif (ref $from eq 'HASH') {
116 return $self->_make_as($from);
118 return $from; # would love to quote here but _table ends up getting called
119 # twice during an ->select without a limit clause due to
120 # the way S::A::Limit->select works. should maybe consider
121 # bypassing this and doing S::A::select($self, ...) in
122 # our select method above. meantime, quoting shims have
123 # been added to select/insert/update/delete here
128 my ($self, $from, @join) = @_;
130 push(@sqlf, $self->_make_as($from));
131 foreach my $j (@join) {
134 # check whether a join type exists
135 my $join_clause = '';
136 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
137 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
139 $join_clause = ' JOIN ';
141 push(@sqlf, $join_clause);
143 if (ref $to eq 'ARRAY') {
144 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
146 push(@sqlf, $self->_make_as($to));
148 push(@sqlf, ' ON ', $self->_join_condition($on));
150 return join('', @sqlf);
154 my ($self, $from) = @_;
155 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
156 reverse each %{$self->_skip_options($from)});
160 my ($self, $hash) = @_;
162 $clean_hash->{$_} = $hash->{$_}
163 for grep {!/^-/} keys %$hash;
167 sub _join_condition {
168 my ($self, $cond) = @_;
169 if (ref $cond eq 'HASH') {
172 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
174 return $self->_recurse_where(\%j);
175 } elsif (ref $cond eq 'ARRAY') {
176 return join(' OR ', map { $self->_join_condition($_) } @$cond);
178 die "Can't handle this yet!";
183 my ($self, $label) = @_;
184 return '' unless defined $label;
185 return "*" if $label eq '*';
186 return $label unless $self->{quote_char};
187 if(ref $self->{quote_char} eq "ARRAY"){
188 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
189 if !defined $self->{name_sep};
190 my $sep = $self->{name_sep};
191 return join($self->{name_sep},
192 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
193 split(/\Q$sep\E/,$label));
195 return $self->SUPER::_quote($label);
201 $_[0] =~ s/SELECT (.*?) FROM/
202 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
203 $self->SUPER::_RowNum(@_);
206 # Accessor for setting limit dialect. This is useful
207 # for JDBC-bridge among others where the remote SQL-dialect cannot
208 # be determined by the name of the driver alone.
212 $self->{limit_dialect} = shift if @_;
213 return $self->{limit_dialect};
218 $self->{quote_char} = shift if @_;
219 return $self->{quote_char};
224 $self->{name_sep} = shift if @_;
225 return $self->{name_sep};
228 } # End of BEGIN block
230 use base qw/DBIx::Class/;
232 __PACKAGE__->load_components(qw/AccessorGroup/);
234 __PACKAGE__->mk_group_accessors('simple' =>
235 qw/_connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugobj
236 cursor on_connect_do transaction_depth/);
239 my $new = bless({}, ref $_[0] || $_[0]);
240 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
241 $new->transaction_depth(0);
243 $new->debugobj(new DBIx::Class::Storage::Statistics());
246 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
247 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
248 $fh = IO::File->new($1, 'w')
249 or $new->throw_exception("Cannot open trace file $1");
251 $fh = IO::File->new('>&STDERR');
254 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
258 sub throw_exception {
259 my ($self, $msg) = @_;
265 DBIx::Class::Storage::DBI - DBI storage handler
271 This class represents the connection to the database
279 Connection information arrayref. Can either be the same arguments
280 one would pass to DBI->connect, or a code-reference which returns
281 a connected database handle. In either case, there is an optional
282 final element in the arrayref, which can hold a hashref of
283 connection-specific Storage::DBI options. These include
284 C<on_connect_do>, and the sql_maker options C<limit_dialect>,
285 C<quote_char>, and C<name_sep>. Examples:
287 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
288 ->connect_info(sub { DBI->connect(...) });
289 ->connect_info([ 'dbi:Pg:dbname=foo',
293 { quote_char => q{`}, name_sep => q{@} },
298 Executes the sql statements given as a listref on every db connect.
302 Specifies what characters to use to quote table and column names. If
303 you use this you will want to specify L<name_sep> as well.
305 quote_char expectes either a single character, in which case is it is placed
306 on either side of the table/column, or an array of length 2 in which case the
307 table/column name is placed between the elements.
309 For example under MySQL you'd use C<quote_char('`')>, and user SQL Server you'd
310 use C<quote_char(qw/[ ]/)>.
314 This only needs to be used in conjunction with L<quote_char>, and is used to
315 specify the charecter that seperates elements (schemas, tables, columns) from
316 each other. In most cases this is simply a C<.>.
320 Causes SQL trace information to be emitted on the C<debugobj> object.
321 (or C<STDERR> if C<debugobj> has not specifically been set).
325 Set or retrieve the filehandle used for trace/debug output. This should be
326 an IO::Handle compatible ojbect (only the C<print> method is used. Initially
327 set to be STDERR - although see information on the
328 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
335 if ($self->debugobj->can('debugfh')) {
336 return $self->debugobj->debugfh(@_);
342 Sets or retrieves the object used for metric collection. Defaults to an instance
343 of L<DBIx::Class::Storage::Statistics> that is campatible with the original
344 method of using a coderef as a callback. See the aforementioned Statistics
345 class for more information.
349 Sets a callback to be executed each time a statement is run; takes a sub
350 reference. Callback is executed as $sub->($op, $info) where $op is
351 SELECT/INSERT/UPDATE/DELETE and $info is what would normally be printed.
353 See L<debugobj> for a better way.
360 if ($self->debugobj->can('callback')) {
361 return $self->debugobj->callback(@_);
368 if( $self->connected ) {
369 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
370 $self->_dbh->disconnect;
378 if(my $dbh = $self->_dbh) {
379 if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
380 $self->_sql_maker(undef);
381 return $self->_dbh(undef);
383 elsif($self->_conn_pid != $$) {
384 $self->_dbh->{InactiveDestroy} = 1;
385 $self->_sql_maker(undef);
386 return $self->_dbh(undef)
388 return ($dbh->FETCH('Active') && $dbh->ping);
394 sub ensure_connected {
397 unless ($self->connected) {
398 $self->_populate_dbh;
404 Returns the dbh - a data base handle of class L<DBI>.
411 $self->ensure_connected;
415 sub _sql_maker_args {
418 return ( limit_dialect => $self->dbh );
423 unless ($self->_sql_maker) {
424 $self->_sql_maker(new DBIC::SQL::Abstract( $self->_sql_maker_args ));
426 return $self->_sql_maker;
430 my ($self, $info_arg) = @_;
433 my $info = [ @$info_arg ]; # copy because we can alter it
434 my $last_info = $info->[-1];
435 if(ref $last_info eq 'HASH') {
437 if(my $on_connect_do = $last_info->{on_connect_do}) {
439 $self->on_connect_do($on_connect_do);
441 for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
442 if(my $opt_val = $last_info->{$sql_maker_opt}) {
444 $self->sql_maker->$sql_maker_opt($opt_val);
448 # remove our options hashref if it was there, to avoid confusing
449 # DBI in the case the user didn't use all 4 DBI options, as in:
450 # [ 'dbi:SQLite:foo.db', { quote_char => q{`} } ]
451 pop(@$info) if $used;
454 $self->_connect_info($info);
457 $self->_connect_info;
462 my @info = @{$self->_connect_info || []};
463 $self->_dbh($self->_connect(@info));
464 my $driver = $self->_dbh->{Driver}->{Name};
465 eval "require DBIx::Class::Storage::DBI::${driver}";
467 bless $self, "DBIx::Class::Storage::DBI::${driver}";
468 $self->_rebless() if $self->can('_rebless');
470 # if on-connect sql statements are given execute them
471 foreach my $sql_statement (@{$self->on_connect_do || []}) {
472 $self->debugobj->query_start($sql_statement) if $self->debug();
473 $self->_dbh->do($sql_statement);
474 $self->debugobj->query_end($sql_statement) if $self->debug();
477 $self->_conn_pid($$);
478 $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
482 my ($self, @info) = @_;
484 $self->throw_exception("You failed to provide any connection info")
487 my ($old_connect_via, $dbh);
489 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
490 $old_connect_via = $DBI::connect_via;
491 $DBI::connect_via = 'connect';
495 if(ref $info[0] eq 'CODE') {
499 $dbh = DBI->connect(@info);
503 $DBI::connect_via = $old_connect_via if $old_connect_via;
506 $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
514 Calls begin_work on the current dbh.
516 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
517 an entire code block to be executed transactionally.
523 if ($self->{transaction_depth}++ == 0) {
524 my $dbh = $self->dbh;
525 if ($dbh->{AutoCommit}) {
526 $self->debugobj->txn_begin()
535 Issues a commit against the current dbh.
541 my $dbh = $self->dbh;
542 if ($self->{transaction_depth} == 0) {
543 unless ($dbh->{AutoCommit}) {
544 $self->debugobj->txn_commit()
550 if (--$self->{transaction_depth} == 0) {
551 $self->debugobj->txn_commit()
560 Issues a rollback against the current dbh. A nested rollback will
561 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
562 which allows the rollback to propagate to the outermost transaction.
570 my $dbh = $self->dbh;
571 if ($self->{transaction_depth} == 0) {
572 unless ($dbh->{AutoCommit}) {
573 $self->debugobj->txn_rollback()
579 if (--$self->{transaction_depth} == 0) {
580 $self->debugobj->txn_rollback()
585 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
592 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
593 $error =~ /$exception_class/ and $self->throw_exception($error);
594 $self->{transaction_depth} = 0; # ensure that a failed rollback
595 $self->throw_exception($error); # resets the transaction depth
600 my ($self, $op, $extra_bind, $ident, @args) = @_;
601 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
602 unshift(@bind, @$extra_bind) if $extra_bind;
604 my @debug_bind = map { defined $_ ? qq{'$_'} : q{'NULL'} } @bind;
605 $self->debugobj->query_start($sql, @debug_bind);
607 my $sth = eval { $self->sth($sql,$op) };
610 $self->throw_exception(
611 'no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql"
614 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
618 $rv = eval { $sth->execute(@bind) };
621 $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
624 $self->throw_exception("'$sql' did not generate a statement.");
627 my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
628 $self->debugobj->query_end($sql, @debug_bind);
630 return (wantarray ? ($rv, $sth, @bind) : $rv);
634 my ($self, $ident, $to_insert) = @_;
635 $self->throw_exception(
636 "Couldn't insert ".join(', ',
637 map "$_ => $to_insert->{$_}", keys %$to_insert
639 ) unless ($self->_execute('insert' => [], $ident, $to_insert));
644 return shift->_execute('update' => [], @_);
648 return shift->_execute('delete' => [], @_);
652 my ($self, $ident, $select, $condition, $attrs) = @_;
653 my $order = $attrs->{order_by};
654 if (ref $condition eq 'SCALAR') {
655 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
657 if (exists $attrs->{group_by} || $attrs->{having}) {
659 group_by => $attrs->{group_by},
660 having => $attrs->{having},
661 ($order ? (order_by => $order) : ())
664 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
665 if ($attrs->{software_limit} ||
666 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
667 $attrs->{software_limit} = 1;
669 $self->throw_exception("rows attribute must be positive if present")
670 if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
671 push @args, $attrs->{rows}, $attrs->{offset};
673 return $self->_execute(@args);
678 my ($ident, $select, $condition, $attrs) = @_;
679 return $self->cursor->new($self, \@_, $attrs);
682 # Need to call finish() to work round broken DBDs
686 my ($rv, $sth, @bind) = $self->_select(@_);
687 my @row = $sth->fetchrow_array;
693 my ($self, $sql) = @_;
694 # 3 is the if_active parameter which avoids active sth re-use
695 return $self->dbh->prepare_cached($sql, {}, 3);
698 =head2 columns_info_for
700 Returns database type info for a given table columns.
704 sub columns_info_for {
705 my ($self, $table) = @_;
707 my $dbh = $self->dbh;
709 if ($dbh->can('column_info')) {
711 my $old_raise_err = $dbh->{RaiseError};
712 my $old_print_err = $dbh->{PrintError};
713 $dbh->{RaiseError} = 1;
714 $dbh->{PrintError} = 0;
716 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
717 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
719 while ( my $info = $sth->fetchrow_hashref() ){
721 $column_info{data_type} = $info->{TYPE_NAME};
722 $column_info{size} = $info->{COLUMN_SIZE};
723 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
724 $column_info{default_value} = $info->{COLUMN_DEF};
725 my $col_name = $info->{COLUMN_NAME};
726 $col_name =~ s/^\"(.*)\"$/$1/;
728 $result{$col_name} = \%column_info;
731 $dbh->{RaiseError} = $old_raise_err;
732 $dbh->{PrintError} = $old_print_err;
733 return \%result if !$@;
737 my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
739 my @columns = @{$sth->{NAME_lc}};
740 for my $i ( 0 .. $#columns ){
742 my $type_num = $sth->{TYPE}->[$i];
744 if(defined $type_num && $dbh->can('type_info')) {
745 my $type_info = $dbh->type_info($type_num);
746 $type_name = $type_info->{TYPE_NAME} if $type_info;
748 $column_info{data_type} = $type_name ? $type_name : $type_num;
749 $column_info{size} = $sth->{PRECISION}->[$i];
750 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
752 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
753 $column_info{data_type} = $1;
754 $column_info{size} = $2;
757 $result{$columns[$i]} = \%column_info;
764 my ($self, $row) = @_;
766 return $self->dbh->func('last_insert_rowid');
770 sub sqlt_type { shift->dbh->{Driver}->{Name} }
774 my ($self, $schema, $databases, $version, $dir, $sqltargs) = @_;
776 if(!$dir || !-d $dir)
778 warn "No directory given, using ./\n";
781 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
782 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
783 $version ||= $schema->VERSION || '1.x';
785 eval "use SQL::Translator";
786 $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
788 my $sqlt = SQL::Translator->new({
792 foreach my $db (@$databases)
795 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
796 # $sqlt->parser_args({'DBIx::Class' => $schema);
797 $sqlt->data($schema);
798 $sqlt->producer($db);
801 my $filename = $schema->ddl_filename($db, $dir, $version);
804 $self->throw_exception("$filename already exists, skipping $db");
807 open($file, ">$filename")
808 or $self->throw_exception("Can't open $filename for writing ($!)");
809 my $output = $sqlt->translate;
811 # print join(":", keys %{$schema->source_registrations});
812 # print Dumper($sqlt->schema);
815 $self->throw_exception("Failed to translate to $db. (" . $sqlt->error . ")");
824 sub deployment_statements {
825 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
826 $type ||= $self->sqlt_type;
827 $version ||= $schema->VERSION || '1.x';
829 eval "use SQL::Translator";
832 eval "use SQL::Translator::Parser::DBIx::Class;";
833 $self->throw_exception($@) if $@;
834 eval "use SQL::Translator::Producer::${type};";
835 $self->throw_exception($@) if $@;
836 my $tr = SQL::Translator->new(%$sqltargs);
837 SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
838 return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
841 my $filename = $schema->ddl_filename($type, $dir, $version);
844 # $schema->create_ddl_dir([ $type ], $version, $dir, $sqltargs);
845 $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
849 open($file, "<$filename")
850 or $self->throw_exception("Can't open $filename ($!)");
854 return join('', @rows);
859 my ($self, $schema, $type, $sqltargs) = @_;
860 foreach my $statement ( $self->deployment_statements($schema, $type, undef, undef, $sqltargs) ) {
861 for ( split(";\n", $statement)) {
862 next if($_ =~ /^--/);
864 # next if($_ =~ /^DROP/m);
865 next if($_ =~ /^BEGIN TRANSACTION/m);
866 next if($_ =~ /^COMMIT/m);
867 $self->debugobj->query_begin($_) if $self->debug;
868 $self->dbh->do($_) or warn "SQL was:\n $_";
869 $self->debugobj->query_end($_) if $self->debug;
874 sub datetime_parser {
876 return $self->{datetime_parser} ||= $self->build_datetime_parser(@_);
879 sub datetime_parser_type { "DateTime::Format::MySQL"; }
881 sub build_datetime_parser {
883 my $type = $self->datetime_parser_type(@_);
885 $self->throw_exception("Couldn't load ${type}: $@") if $@;
889 sub DESTROY { shift->disconnect }
893 =head1 ENVIRONMENT VARIABLES
895 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
897 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
898 is produced (as when the L<debug> method is set).
900 If the value is of the form C<1=/path/name> then the trace output is
901 written to the file C</path/name>.
903 This environment variable is checked when the storage object is first
904 created (when you call connect on your schema). So, run-time changes
905 to this environment variable will not take effect unless you also
906 re-connect on your schema.
910 Matt S. Trout <mst@shadowcatsystems.co.uk>
912 Andy Grundman <andy@hybridized.org>
916 You may distribute this code under the same terms as Perl itself.