📄 proxy.pm
字号:
'TYPE' => 'cache_only', 'PRECISION' => 'cache_only', 'SCALE' => 'cache_only', 'NUM_OF_FIELDS' => 'cache_only', 'NUM_OF_PARAMS' => 'cache_only');*AUTOLOAD = \&DBD::Proxy::db::AUTOLOAD;sub execute ($@) { my $sth = shift; my $params = @_ ? \@_ : $sth->{'proxy_params'}; # new execute, so delete any cached rows from previous execute undef $sth->{'proxy_data'}; undef $sth->{'proxy_rows'}; my $rsth = $sth->{proxy_sth}; my $dbh = $sth->FETCH('Database'); my $proto_ver = $dbh->{proxy_proto_ver}; my ($numRows, @outData); local $SIG{__DIE__} = 'DEFAULT'; local $@; if ( $proto_ver > 1 ) { ($numRows, @outData) = eval { $rsth->execute($params, $proto_ver) }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; # Attributes passed back only on the first execute() of a statement. unless ($sth->{proxy_attr_cache}->{cache_filled}) { my ($numFields, $numParams, $names, $types) = splice(@outData, 0, 4); $sth->{'proxy_attr_cache'} = { 'NUM_OF_FIELDS' => $numFields, 'NUM_OF_PARAMS' => $numParams, 'NAME' => $names, 'cache_filled' => 1 }; $sth->SUPER::STORE('NUM_OF_FIELDS' => $numFields); $sth->SUPER::STORE('NUM_OF_PARAMS' => $numParams); } } else { if ($rsth) { ($numRows, @outData) = eval { $rsth->execute($params, $proto_ver) }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; } else { my $rdbh = $dbh->{'proxy_dbh'}; # Legacy prepare is actually prepare + first execute on the server. ($rsth, @outData) = eval { $rdbh->prepare($sth->{'Statement'}, $sth->{'proxy_attr'}, $params, $proto_ver) }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; return DBD::Proxy::proxy_set_err($sth, "Constructor didn't return a handle: $rsth") unless ($rsth =~ /^((?:\w+|\:\:)+)=(\w+)/); my $client = $dbh->{'proxy_client'}; $rsth = RPC::PlClient::Object->new($1, $client, $rsth); my ($numFields, $numParams, $names, $types) = splice(@outData, 0, 4); $sth->{'proxy_sth'} = $rsth; $sth->{'proxy_attr_cache'} = { 'NUM_OF_FIELDS' => $numFields, 'NUM_OF_PARAMS' => $numParams, 'NAME' => $names }; $sth->SUPER::STORE('NUM_OF_FIELDS' => $numFields); $sth->SUPER::STORE('NUM_OF_PARAMS' => $numParams); $numRows = shift @outData; } } # Always condition active flag. $sth->SUPER::STORE('Active' => 1) if $sth->FETCH('NUM_OF_FIELDS'); # is SELECT $sth->{'proxy_rows'} = $numRows; # Any remaining items are output params. if (@outData) { foreach my $p (@$params) { if (ref($p->[0])) { my $ref = shift @outData; ${$p->[0]} = $$ref; } } } $sth->{'proxy_rows'} || '0E0';}sub fetch ($) { my $sth = shift; my $data = $sth->{'proxy_data'}; $sth->{'proxy_rows'} = 0 unless defined $sth->{'proxy_rows'}; if(!$data || !@$data) { return undef unless $sth->SUPER::FETCH('Active'); my $rsth = $sth->{'proxy_sth'}; if (!$rsth) { die "Attempt to fetch row without execute"; } my $num_rows = $sth->FETCH('RowCacheSize') || 20; local $SIG{__DIE__} = 'DEFAULT'; local $@; my @rows = eval { $rsth->fetch($num_rows) }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; unless (@rows == $num_rows) { undef $sth->{'proxy_data'}; # server side has already called finish $sth->SUPER::STORE(Active => 0); } return undef unless @rows; $sth->{'proxy_data'} = $data = [@rows]; } my $row = shift @$data; $sth->SUPER::STORE(Active => 0) if ( $sth->{proxy_cache_only} and !@$data ); $sth->{'proxy_rows'}++; return $sth->_set_fbav($row);}*fetchrow_arrayref = \&fetch;sub rows ($) { my $rows = shift->{'proxy_rows'}; return (defined $rows) ? $rows : -1;}sub finish ($) { my($sth) = @_; return 1 unless $sth->SUPER::FETCH('Active'); my $rsth = $sth->{'proxy_sth'}; $sth->SUPER::STORE('Active' => 0); return 0 unless $rsth; # Something's out of sync my $no_finish = exists($sth->{'proxy_no_finish'}) ? $sth->{'proxy_no_finish'} : $sth->FETCH('Database')->{'proxy_no_finish'}; unless ($no_finish) { local $SIG{__DIE__} = 'DEFAULT'; local $@; my $result = eval { $rsth->finish() }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; return $result; } 1;}sub STORE ($$$) { my($sth, $attr, $val) = @_; my $type = $ATTR{$attr} || 'remote'; if ($attr =~ /^proxy_/ || $type eq 'inherited') { $sth->{$attr} = $val; return 1; } if ($type eq 'cache_only') { return 0; } if ($type eq 'remote' || $type eq 'cached') { my $rsth = $sth->{'proxy_sth'} or return undef; local $SIG{__DIE__} = 'DEFAULT'; local $@; my $result = eval { $rsth->STORE($attr => $val) }; return DBD::Proxy::proxy_set_err($sth, $@) if ($@); return $result if $type eq 'remote'; # else fall through to cache locally } return $sth->SUPER::STORE($attr => $val);}sub FETCH ($$) { my($sth, $attr) = @_; if ($attr =~ /^proxy_/) { return $sth->{$attr}; } my $type = $ATTR{$attr} || 'remote'; if ($type eq 'inherited') { if (exists($sth->{$attr})) { return $sth->{$attr}; } return $sth->FETCH('Database')->{$attr}; } if ($type eq 'cache_only' && exists($sth->{'proxy_attr_cache'}->{$attr})) { return $sth->{'proxy_attr_cache'}->{$attr}; } if ($type ne 'local') { my $rsth = $sth->{'proxy_sth'} or return undef; local $SIG{__DIE__} = 'DEFAULT'; local $@; my $result = eval { $rsth->FETCH($attr) }; return DBD::Proxy::proxy_set_err($sth, $@) if $@; return $result; } elsif ($attr eq 'RowsInCache') { my $data = $sth->{'proxy_data'}; $data ? @$data : 0; } else { $sth->SUPER::FETCH($attr); }}sub bind_param ($$$@) { my $sth = shift; my $param = shift; $sth->{'proxy_params'}->[$param-1] = [@_];}*bind_param_inout = \&bind_param;sub DESTROY { my $sth = shift; $sth->finish if $sth->SUPER::FETCH('Active');}1;__END__=head1 NAMEDBD::Proxy - A proxy driver for the DBI=head1 SYNOPSIS use DBI; $dbh = DBI->connect("dbi:Proxy:hostname=$host;port=$port;dsn=$db", $user, $passwd); # See the DBI module documentation for full details=head1 DESCRIPTIONDBD::Proxy is a Perl module for connecting to a database via a remoteDBI driver. See L<DBD::Gofer> for an alternative with different trade-offs.This is of course not needed for DBI drivers which alreadysupport connecting to a remote database, but there are engines whichdon't offer network connectivity.Another application is offering database access through a firewall, asthe driver offers query based restrictions. For example you canrestrict queries to exactly those that are used in a given CGIapplication.Speaking of CGI, another application is (or rather, will be) to reducethe database connect/disconnect overhead from CGI scripts by usingproxying the connect_cached method. The proxy server will hold thedatabase connections open in a cache. The CGI script then trades thedatabase connect/disconnect overhead for the DBD::Proxyconnect/disconnect overhead which is typically much less.I<Note that the connect_cached method is new and still experimental.>=head1 CONNECTING TO THE DATABASEBefore connecting to a remote database, you must ensure, that a Proxyserver is running on the remote machine. There's no default port, soyou have to ask your system administrator for the port number. SeeL<DBI::ProxyServer> for details.Say, your Proxy server is running on machine "alpha", port 3334, andyou'd like to connect to an ODBC database called "mydb" as user "joe"with password "hello". When using DBD::ODBC directly, you'd do a $dbh = DBI->connect("DBI:ODBC:mydb", "joe", "hello");With DBD::Proxy this becomes $dsn = "DBI:Proxy:hostname=alpha;port=3334;dsn=DBI:ODBC:mydb"; $dbh = DBI->connect($dsn, "joe", "hello");You see, this is mainly the same. The DBD::Proxy module will create aconnection to the Proxy server on "alpha" which in turn will connectto the ODBC database.Refer to the L<DBI> documentation on the C<connect> method for a wayto automatically use DBD::Proxy without having to change your code.DBD::Proxy's DSN string has the format $dsn = "DBI:Proxy:key1=val1; ... ;keyN=valN;dsn=valDSN";In other words, it is a collection of key/value pairs. The followingkeys are recognized:=over 4=item hostname=item portHostname and port of the Proxy server; these keys must be present,no defaults. Example: hostname=alpha;port=3334=item dsnThe value of this attribute will be used as a dsn name by the Proxyserver. Thus it must have the format C<DBI:driver:...>, in particularit will contain colons. The I<dsn> value may contain semicolons, hencethis key *must* be the last and it's value will be the completeremaining part of the dsn. Example: dsn=DBI:ODBC:mydb=item cipher=item key=item usercipher=item userkeyBy using these fields you can enable encryption. If you set,for example, cipher=$class;key=$key(note the semicolon) then DBD::Proxy will create a new cipher objectby executing $cipherRef = $class->new(pack("H*", $key));and pass this object to the RPC::PlClient module when creating aclient. See L<RPC::PlClient>. Example: cipher=IDEA;key=97cd2375efa329aceef2098babdc9721The usercipher/userkey attributes allow you to use two phase encryption:The cipher/key encryption will be used in the login and authorisationphase. Once the client is authorised, he will change to usercipher/userkeyencryption. Thus the cipher/key pair is a B<host> based secret, typicallyless secure than the usercipher/userkey secret and readable by anyone.The usercipher/userkey secret is B<your> private secret.Of course encryption requires an appropriately configured server. See<DBD::ProxyServer/CONFIGURATION FILE>.=item debugTurn on debugging mode=item stderrThis attribute will set the corresponding attribute of the RPC::PlClientobject, thus logging will not use syslog(), but redirected to stderr.This is the default under Windows. stderr=1=item logfileSimilar to the stderr attribute, but output will be redirected to thegiven file. logfile=/dev/null=item RowCacheSizeThe DBD::Proxy driver supports this attribute (which is DBI standard,as of DBI 1.02). It's used to reduce network round-trips by fetchingmultiple rows in one go. The current default value is 20, but this maychange.=item proxy_no_finishThis attribute can be used to reduce network traffic: If theapplication is calling $sth->finish() then the proxy tells the serverto finish the remote statement handle. Of course this slows down thingsquite a lot, but is prefectly good for reducing memory usage withpersistent connections.However, if you set the I<proxy_no_finish> attribute to a TRUE value,either in the database handle or in the statement handle, then finish()calls will be supressed. This is what you want, for example, in smalland fast CGI applications.=item proxy_quoteThis attribute can be used to reduce network traffic: By default callsto $dbh->quote() are passed to the remote driver. Of course this slowsdown things quite a lot, but is the safest default behaviour.However, if you set the I<proxy_quote> attribute to the value 'C<local>'either in the database handle or in the statement handle, and the callto quote has only one parameter, then the local default DBI quotemethod will be used (which will be faster but may be wrong).=back=head1 KNOWN ISSUES=head2 Unproxied method callsIf a method isn't being proxied, try declaring a stub sub in the appropriatepackage (DBD::Proxy::db for a dbh method, and DBD::Proxy::st for an sth method).For example: sub DBD::Proxy::db::selectall_arrayref;That will enable selectall_arrayref to be proxied.Currently many methods aren't explicitly proxied and so you get the DBI'sdefault methods executed on the client.Some of those methods, like selectall_arrayref, may then call other methodsthat are proxied (selectall_arrayref calls fetchall_arrayref which calls fetchwhich is proxied). So things may appear to work but operate more slowly thanthe could.This may all change in a later version.=head2 Complex handle attributesSometimes handles are having complex attributes like hash refs orarray refs and not simple strings or integers. For example, withDBD::CSV, you would like to write something like $dbh->{"csv_tables"}->{"passwd"} = { "sep_char" => ":", "eol" => "\n";The above example would advice the CSV driver to assume the file"passwd" to be in the format of the /etc/passwd file: Colons asseparators and a line feed without carriage return as lineterminator.Surprisingly this example doesn't work with the proxy driver. To understandthe reasons, you should consider the following: The Perl compiler isexecuting the above example in two steps:=over=item 1The first step is fetching the value of the key "csv_tables" in thehandle $dbh. The value returned is complex, a hash ref.=item 2The second step is storing some value (the right hand side of theassignment) as the key "passwd" in the hash ref from step 1.=backThis becomes a little bit clearer, if we rewrite the above code: $tables = $dbh->{"csv_tables"}; $tables->{"passwd"} = { "sep_char" => ":", "eol" => "\n";While the examples work fine without the proxy, the fail due to asubtile difference in step 1: By DBI magic, the hash ref$dbh->{'csv_tables'} is returned from the server to the client.The client creates a local copy. This local copy is the result ofstep 1. In other words, step 2 modifies a local copy of the hash ref,but not the server's hash ref.The workaround is storing the modified local copy back to the server: $tables = $dbh->{"csv_tables"}; $tables->{"passwd"} = { "sep_char" => ":", "eol" => "\n"; $dbh->{"csv_tables"} = $tables;=head1 AUTHOR AND COPYRIGHTThis module is Copyright (c) 1997, 1998 Jochen Wiedmann Am Eisteich 9 72555 Metzingen Germany Email: joe@ispsoft.de Phone: +49 7123 14887The DBD::Proxy module is free software; you can redistribute it and/ormodify it under the same terms as Perl itself. In particular permissionis granted to Tim Bunce for distributing this as a part of the DBI.=head1 SEE ALSOL<DBI>, L<RPC::PlClient>, L<Storable>=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -