X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FStorage%2FDBI.pm;h=c26525d5ee5ca4165e24fb752043b3bb6145745b;hb=bbdda28109ffb2442af84b3cbe5c4921714a52dd;hp=a800954e5e9ffa5cf479fbf82f10bf75a461da5e;hpb=bca6956d7eb1196ae767271688f915d7ab078a10;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Storage/DBI.pm b/lib/DBIx/Class/Storage/DBI.pm index a800954..c26525d 100644 --- a/lib/DBIx/Class/Storage/DBI.pm +++ b/lib/DBIx/Class/Storage/DBI.pm @@ -11,19 +11,25 @@ use Carp::Clan qw/^DBIx::Class/; use DBI; use DBIx::Class::Storage::DBI::Cursor; use DBIx::Class::Storage::Statistics; -use Scalar::Util(); -use List::Util(); -use Data::Dumper::Concise(); -use Sub::Name (); +use Scalar::Util qw/refaddr weaken reftype blessed/; +use Data::Dumper::Concise 'Dumper'; +use Sub::Name 'subname'; use Try::Tiny; +use File::Path 'make_path'; +use namespace::clean; -use File::Path (); +# default cursor class, overridable in connect_info attributes +__PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor'); -__PACKAGE__->mk_group_accessors('simple' => - qw/_connect_info _dbi_connect_info _dbh _sql_maker _sql_maker_opts _conn_pid - _conn_tid transaction_depth _dbh_autocommit _driver_determined savepoints - _server_info_hash/ -); +__PACKAGE__->mk_group_accessors('inherited' => qw/sql_maker_class/); +# default +__PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks'); + +__PACKAGE__->mk_group_accessors('simple' => qw/ + _connect_info _dbi_connect_info _dbic_connect_attributes _driver_determined + _dbh _dbh_details _conn_pid _conn_tid _sql_maker _sql_maker_opts + transaction_depth _dbh_autocommit savepoints +/); # the values for these accessors are picked out (and deleted) from # the attribute hashref passed to connect_info @@ -34,40 +40,59 @@ my @storage_options = qw/ __PACKAGE__->mk_group_accessors('simple' => @storage_options); -# default cursor class, overridable in connect_info attributes -__PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor'); +# capability definitions, using a 2-tiered accessor system +# The rationale is: +# +# A driver/user may define _use_X, which blindly without any checks says: +# "(do not) use this capability", (use_dbms_capability is an "inherited" +# type accessor) +# +# If _use_X is undef, _supports_X is then queried. This is a "simple" style +# accessor, which in turn calls _determine_supports_X, and stores the return +# in a special slot on the storage object, which is wiped every time a $dbh +# reconnection takes place (it is not guaranteed that upon reconnection we +# will get the same rdbms version). _determine_supports_X does not need to +# exist on a driver, as we ->can for it before calling. + +my @capabilities = (qw/insert_returning placeholders typeless_placeholders/); +__PACKAGE__->mk_group_accessors( dbms_capability => map { "_supports_$_" } @capabilities ); +__PACKAGE__->mk_group_accessors( use_dbms_capability => map { "_use_$_" } @capabilities ); -__PACKAGE__->mk_group_accessors('inherited' => qw/ - sql_maker_class - _supports_insert_returning -/); -__PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks'); # Each of these methods need _determine_driver called before itself # in order to function reliably. This is a purely DRY optimization +# +# get_(use)_dbms_capability need to be called on the correct Storage +# class, as _use_X may be hardcoded class-wide, and _supports_X calls +# _determine_supports_X which obv. needs a correct driver as well my @rdbms_specific_methods = qw/ deployment_statements sqlt_type + sql_maker build_datetime_parser datetime_parser_type + insert insert_bulk update delete select select_single + + get_use_dbms_capability + get_dbms_capability /; for my $meth (@rdbms_specific_methods) { my $orig = __PACKAGE__->can ($meth) - or next; + or die "$meth is not a ::Storage::DBI method!"; no strict qw/refs/; no warnings qw/redefine/; - *{__PACKAGE__ ."::$meth"} = Sub::Name::subname $meth => sub { - if (not $_[0]->_driver_determined) { + *{__PACKAGE__ ."::$meth"} = subname $meth => sub { + if (not $_[0]->_driver_determined and not $_[0]->{_in_determine_driver}) { $_[0]->_determine_driver; goto $_[0]->can($meth); } @@ -113,6 +138,7 @@ sub new { $new->transaction_depth(0); $new->_sql_maker_opts({}); + $new->_dbh_details({}); $new->{savepoints} = []; $new->{_in_dbh_do} = 0; $new->{_dbh_gen} = 0; @@ -581,6 +607,11 @@ sub connect_info { $self->_dbi_connect_info([@args, %attrs && !(ref $args[0] eq 'CODE') ? \%attrs : ()]); + # FIXME - dirty: + # save attributes them in a separate accessor so they are always + # introspectable, even in case of a CODE $dbhmaker + $self->_dbic_connect_attributes (\%attrs); + return $self->_connect_info; } @@ -722,39 +753,26 @@ sub dbh_do { my $dbh = $self->_get_dbh; - return $self->$code($dbh, @_) if $self->{_in_dbh_do} - || $self->{transaction_depth}; + return $self->$code($dbh, @_) + if ( $self->{_in_dbh_do} || $self->{transaction_depth} ); local $self->{_in_dbh_do} = 1; - my @result; - my $want_array = wantarray; + # take a ref instead of a copy, to preserve coderef @_ aliasing semantics + my $args = \@_; + return try { + $self->$code ($dbh, @$args); + } catch { + $self->throw_exception($_) if $self->connected; - eval { + # We were not connected - reconnect and retry, but let any + # exception fall right through this time + carp "Retrying $code after catching disconnected exception: $_" + if $ENV{DBIC_DBIRETRY_DEBUG}; - if($want_array) { - @result = $self->$code($dbh, @_); - } - elsif(defined $want_array) { - $result[0] = $self->$code($dbh, @_); - } - else { - $self->$code($dbh, @_); - } + $self->_populate_dbh; + $self->$code($self->_dbh, @$args); }; - - # ->connected might unset $@ - copy - my $exception = $@; - if(!$exception) { return $want_array ? @result : $result[0] } - - $self->throw_exception($exception) if $self->connected; - - # We were not connected - reconnect and retry, but let any - # exception fall right through this time - carp "Retrying $code after catching disconnected exception: $exception" - if $ENV{DBIC_DBIRETRY_DEBUG}; - $self->_populate_dbh; - $self->$code($self->_dbh, @_); } # This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do. @@ -777,19 +795,22 @@ sub txn_do { my $tried = 0; while(1) { my $exception; - my @args = @_; + + # take a ref instead of a copy, to preserve coderef @_ aliasing semantics + my $args = \@_; + try { $self->_get_dbh; $self->txn_begin; if($want_array) { - @result = $coderef->(@args); + @result = $coderef->(@$args); } elsif(defined $want_array) { - $result[0] = $coderef->(@args); + $result[0] = $coderef->(@$args); } else { - $coderef->(@args); + $coderef->(@$args); } $self->txn_commit; } catch { @@ -982,7 +1003,8 @@ sub _populate_dbh { my @info = @{$self->_dbi_connect_info || []}; $self->_dbh(undef); # in case ->connected failed we might get sent here - $self->_server_info_hash (undef); + $self->_dbh_details({}); # reset everything we know + $self->_dbh($self->_connect(@info)); $self->_conn_pid($$); @@ -1007,20 +1029,57 @@ sub _run_connection_actions { $self->_do_connection_actions(connect_call_ => $_) for @actions; } + + +sub set_use_dbms_capability { + $_[0]->set_inherited ($_[1], $_[2]); +} + +sub get_use_dbms_capability { + my ($self, $capname) = @_; + + my $use = $self->get_inherited ($capname); + return defined $use + ? $use + : do { $capname =~ s/^_use_/_supports_/; $self->get_dbms_capability ($capname) } + ; +} + +sub set_dbms_capability { + $_[0]->_dbh_details->{capability}{$_[1]} = $_[2]; +} + +sub get_dbms_capability { + my ($self, $capname) = @_; + + my $cap = $self->_dbh_details->{capability}{$capname}; + + unless (defined $cap) { + if (my $meth = $self->can ("_determine$capname")) { + $cap = $self->$meth ? 1 : 0; + } + else { + $cap = 0; + } + + $self->set_dbms_capability ($capname, $cap); + } + + return $cap; +} + sub _server_info { my $self = shift; - unless ($self->_server_info_hash) { + my $info; + unless ($info = $self->_dbh_details->{info}) { - my %info; + $info = {}; - my $server_version = do { - local $@; # might be happenin in some sort of destructor - try { $self->_get_server_version }; - }; + my $server_version = try { $self->_get_server_version }; if (defined $server_version) { - $info{dbms_version} = $server_version; + $info->{dbms_version} = $server_version; my ($numeric_version) = $server_version =~ /^([\d\.]+)/; my @verparts = split (/\./, $numeric_version); @@ -1038,14 +1097,14 @@ sub _server_info { } push @use_parts, 0 while @use_parts < 3; - $info{normalized_dbms_version} = sprintf "%d.%03d%03d", @use_parts; + $info->{normalized_dbms_version} = sprintf "%d.%03d%03d", @use_parts; } } - $self->_server_info_hash(\%info); + $self->_dbh_details->{info} = $info; } - return $self->_server_info_hash + return $info; } sub _get_server_version { @@ -1067,7 +1126,7 @@ sub _determine_driver { } else { # if connect_info is a CODEREF, we have no choice but to connect if (ref $self->_dbi_connect_info->[0] && - Scalar::Util::reftype($self->_dbi_connect_info->[0]) eq 'CODE') { + reftype $self->_dbi_connect_info->[0] eq 'CODE') { $self->_populate_dbh; $driver = $self->_dbh->{Driver}{Name}; } @@ -1174,7 +1233,6 @@ sub _connect { $DBI::connect_via = 'connect'; } - my $caught; try { if(ref $info[0] eq 'CODE') { $dbh = $info[0]->(); @@ -1183,34 +1241,44 @@ sub _connect { $dbh = DBI->connect(@info); } - if($dbh && !$self->unsafe) { - my $weak_self = $self; - Scalar::Util::weaken($weak_self); - $dbh->{HandleError} = sub { + if (!$dbh) { + die $DBI::errstr; + } + + unless ($self->unsafe) { + + # this odd anonymous coderef dereference is in fact really + # necessary to avoid the unwanted effect described in perl5 + # RT#75792 + sub { + my $weak_self = $_[0]; + weaken $weak_self; + + $_[1]->{HandleError} = sub { if ($weak_self) { $weak_self->throw_exception("DBI Exception: $_[0]"); } else { # the handler may be invoked by something totally out of # the scope of DBIC - croak ("DBI Exception: $_[0]"); + croak ("DBI Exception (unhandled by DBIC, ::Schema GCed): $_[0]"); } - }; + }; + }->($self, $dbh); + $dbh->{ShowErrorStatement} = 1; $dbh->{RaiseError} = 1; $dbh->{PrintError} = 0; } - } catch { - $caught = 1; + } + catch { + $self->throw_exception("DBI Connection failed: $_") + } + finally { + $DBI::connect_via = $old_connect_via if $old_connect_via; }; - $DBI::connect_via = $old_connect_via if $old_connect_via; - - $self->throw_exception("DBI Connection failed: " . ($@||$DBI::errstr)) - if !$dbh || $caught; - $self->_dbh_autocommit($dbh->{AutoCommit}); - $dbh; } @@ -1358,7 +1426,7 @@ sub _dbh_commit { sub txn_rollback { my $self = shift; my $dbh = $self->_dbh; - eval { + try { if ($self->{transaction_depth} == 1) { $self->debugobj->txn_rollback() if ($self->debug); @@ -1376,15 +1444,17 @@ sub txn_rollback { else { die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new; } - }; - if ($@) { - my $error = $@; - my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION"; - $error =~ /$exception_class/ and $self->throw_exception($error); - # ensure that a failed rollback resets the transaction depth - $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1; - $self->throw_exception($error); } + catch { + my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION"; + + if ($_ !~ /$exception_class/) { + # ensure that a failed rollback resets the transaction depth + $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1; + } + + $self->throw_exception($_) + }; } sub _dbh_rollback { @@ -1400,7 +1470,7 @@ sub _dbh_rollback { sub _prep_for_execute { my ($self, $op, $extra_bind, $ident, $args) = @_; - if( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) { + if( blessed $ident && $ident->isa("DBIx::Class::ResultSource") ) { $ident = $ident->from(); } @@ -1479,7 +1549,9 @@ sub _dbh_execute { # Can this fail without throwing an exception anyways??? my $rv = $sth->execute(); - $self->throw_exception($sth->errstr) if !$rv; + $self->throw_exception( + $sth->errstr || $sth->err || 'Unknown error: execute() returned false, but error flags were not set...' + ) if !$rv; $self->_query_end( $sql, @$bind ); @@ -1526,7 +1598,7 @@ sub insert { if ($opts->{returning}) { my @ret_cols = @{$opts->{returning}}; - my @ret_vals = eval { + my @ret_vals = try { local $SIG{__WARN__} = sub {}; my @r = $sth->fetchrow_array; $sth->finish; @@ -1569,9 +1641,9 @@ sub insert_bulk { $cols->[$col_idx], do { local $Data::Dumper::Maxdepth = 1; # don't dump objects, if any - Data::Dumper::Concise::Dumper({ + Dumper { map { $cols->[$_] => $data->[$slice_idx][$_] } (0 .. $#$cols) - }), + }, } ); }; @@ -1629,7 +1701,7 @@ sub insert_bulk { # scope guard my $guard = $self->txn_scope_guard; - $self->_query_start( $sql, ['__BULK__'] ); + $self->_query_start( $sql, [ dummy => '__BULK_INSERT__' ] ); my $sth = $self->sth($sql); my $rv = do { if ($empty_bind) { @@ -1642,7 +1714,7 @@ sub insert_bulk { } }; - $self->_query_end( $sql, ['__BULK__'] ); + $self->_query_end( $sql, [ dummy => '__BULK_INSERT__' ] ); $guard->commit; @@ -1681,16 +1753,27 @@ sub _execute_array { $placeholder_index++; } - my $rv = eval { - $self->_dbh_execute_array($sth, $tuple_status, @extra); + my ($rv, $err); + try { + $rv = $self->_dbh_execute_array($sth, $tuple_status, @extra); + } + catch { + $err = shift; + } + finally { + # Statement must finish even if there was an exception. + try { + $sth->finish + } + catch { + $err = shift unless defined $err + }; }; - my $err = $@ || $sth->errstr; -# Statement must finish even if there was an exception. - eval { $sth->finish }; - $err = $@ unless $err; + $err = $sth->errstr + if (! defined $err and $sth->err); - if ($err) { + if (defined $err) { my $i = 0; ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i]; @@ -1699,11 +1782,10 @@ sub _execute_array { $self->throw_exception(sprintf "%s for populate slice:\n%s", ($tuple_status->[$i][1] || $err), - Data::Dumper::Concise::Dumper({ - map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) - }), + Dumper { map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) }, ); } + return $rv; } @@ -1716,25 +1798,28 @@ sub _dbh_execute_array { sub _dbh_execute_inserts_with_no_binds { my ($self, $sth, $count) = @_; - my $exception; + my $err; try { my $dbh = $self->_get_dbh; local $dbh->{RaiseError} = 1; local $dbh->{PrintError} = 0; $sth->execute foreach 1..$count; - } catch { - $exception = shift; - }; - -# Make sure statement is finished even if there was an exception. - try { - $sth->finish - } catch { - $exception = shift unless defined $exception; + } + catch { + $err = shift; + } + finally { + # Make sure statement is finished even if there was an exception. + try { + $sth->finish + } + catch { + $err = shift unless defined $err; + }; }; - $self->throw_exception($exception) if defined $exception; + $self->throw_exception($err) if defined $err; return $count; } @@ -1921,19 +2006,13 @@ sub _select_args { } # adjust limits - if ( - $attrs->{software_limit} - || - $sql_maker->_default_limit_syntax eq "GenericSubQ" - ) { - $attrs->{software_limit} = 1; - } - else { + if (defined $attrs->{rows}) { $self->throw_exception("rows attribute must be positive if present") - if (defined($attrs->{rows}) && !($attrs->{rows} > 0)); - + unless $attrs->{rows} > 0; + } + elsif (defined $attrs->{offset}) { # MySQL actually recommends this approach. I cringe. - $attrs->{rows} = 2**48 if not defined $attrs->{rows} and defined $attrs->{offset}; + $attrs->{rows} = $sql_maker->__max_int; } my @limit; @@ -2069,7 +2148,8 @@ sub _dbh_columns_info_for { if ($dbh->can('column_info')) { my %result; - eval { + my $caught; + try { my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table); my $sth = $dbh->column_info( undef,$schema, $tab, '%' ); $sth->execute(); @@ -2084,8 +2164,10 @@ sub _dbh_columns_info_for { $result{$col_name} = \%column_info; } + } catch { + $caught = 1; }; - return \%result if !$@ && scalar keys %result; + return \%result if !$caught && scalar keys %result; } my %result; @@ -2135,7 +2217,7 @@ Return the row id of the last insert. sub _dbh_last_insert_id { my ($self, $dbh, $source, $col) = @_; - my $id = eval { $dbh->last_insert_id (undef, undef, $source->name, $col) }; + my $id = try { $dbh->last_insert_id (undef, undef, $source->name, $col) }; return $id if defined $id; @@ -2180,33 +2262,39 @@ sub _native_data_type { } # Check if placeholders are supported at all -sub _placeholders_supported { +sub _determine_supports_placeholders { my $self = shift; my $dbh = $self->_get_dbh; # some drivers provide a $dbh attribute (e.g. Sybase and $dbh->{syb_dynamic_supported}) # but it is inaccurate more often than not - eval { + return try { local $dbh->{PrintError} = 0; local $dbh->{RaiseError} = 1; $dbh->do('select ?', {}, 1); + 1; + } + catch { + 0; }; - return $@ ? 0 : 1; } # Check if placeholders bound to non-string types throw exceptions # -sub _typeless_placeholders_supported { +sub _determine_supports_typeless_placeholders { my $self = shift; my $dbh = $self->_get_dbh; - eval { + return try { local $dbh->{PrintError} = 0; local $dbh->{RaiseError} = 1; # this specifically tests a bind that is NOT a string $dbh->do('select 1 where 1 = ?', {}, 1); + 1; + } + catch { + 0; }; - return $@ ? 0 : 1; } =head2 sqlt_type @@ -2318,8 +2406,13 @@ sub create_ddl_dir { carp "No directory given, using ./\n"; $dir = './'; } else { - -d $dir or File::Path::mkpath($dir) - or $self->throw_exception("create_ddl_dir: $! creating dir '$dir'"); + -d $dir + or + make_path ("$dir") # make_path does not like objects (i.e. Path::Class::Dir) + or + $self->throw_exception( + "Failed to create '$dir': " . ($! || $@ || 'error unknow') + ); } $self->throw_exception ("Directory '$dir' does not exist\n") unless(-d $dir); @@ -2523,14 +2616,13 @@ sub deploy { return if($line =~ /^COMMIT/m); return if $line =~ /^\s+$/; # skip whitespace only $self->_query_start($line); - eval { + try { # do a dbh_do cycle here, as we need some error checking in # place (even though we will ignore errors) $self->dbh_do (sub { $_[1]->do($line) }); + } catch { + carp qq{$_ (running "${line}")}; }; - if ($@) { - carp qq{$@ (running "${line}")}; - } $self->_query_end($line); }; my @statements = $schema->deployment_statements($type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );